How to convert a BsonDocument into a strongly typed object with the official MongoDB C# driver?

前端 未结 4 1062
我寻月下人不归
我寻月下人不归 2021-02-05 05:15

For unit testing purposes, I\'d like to test my class mappings without reading and writing documents into the MongoDB database. To handle special cases such as circular parent

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-05 06:01

    The MongoDB Driver does provide a method for deserializing from Bson to your type. The BsonSerializer can be found in MongoDB.Bson.dll, in the MongoDB.Bson.Serialization namespace.

    You can use the BsonSerializer.Deserialize() method. Some example code would be

    var obj = new MyClass { MyVersion = new Version(1,0,0,0) };
    var bsonObject = obj.ToBsonDocument();
    var myObj = BsonSerializer.Deserialize(bsonObject);
    Console.WriteLine(myObj);
    

    Where MyClass is defined as

    public class MyClass
    {
        public Version MyVersion {get; set;}
    }
    

    I hope this helps.

提交回复
热议问题