Convert .NET Guid to MongoDB ObjectID

后端 未结 4 1509
臣服心动
臣服心动 2021-02-03 22:11

How can I convert a .NET GUID to a MongoDB ObjectID (in C#). Also, can I convert it back again to the same GUID from the ObjectID?

4条回答
  •  梦毁少年i
    2021-02-03 22:42

    FYI You can convert from an ObjectId to a Guid

        public static Guid AsGuid(this ObjectId oid)
        {
            var bytes = oid.ToByteArray().Concat(new byte[] { 5, 5, 5, 5 }).ToArray();
            Guid gid = new Guid(bytes);
            return gid;
        }
    
        /// 
        /// Only Use to convert a Guid that was once an ObjectId
        /// 
        public static ObjectId AsObjectId(this Guid gid)
        {
            var bytes = gid.ToByteArray().Take(12).ToArray();
            var oid = new ObjectId(bytes);
            return oid;
        }
    

提交回复
热议问题