Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

mongodb

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 / child references and read only properties, I've used BsoncClassMap.RegisterClassMap< MyType>(...) with some custom mappings overriding the default AutoMap(); generated mappings.

Does anyone know how to convert a BsonDocument into the desired strongly typed object without making a round trip to the database? The driver is doing this when going to and from the data store. My goal would be to use the same logic that the MongoDB C# driver is using internally to test the serialization to / from a C# domain object into a BsonDocument.

I'm able to use the Bson extension method ToBsonDocument() to convert a C# object into a BsonDocument? The piece that I'm lacking is the reverse of the process - essentially a BsonDocument.ToObject< MyType>();.

Is this possible with the latest version of the official MongoDB C# driver? It seems like it should be - I'm wondering if I'm just blind and am missing the obvious.

like image 597
user3769062 Avatar asked Jun 23 '14 23:06

user3769062


1 Answers

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<T>() 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<MyClass>(bsonObject); Console.WriteLine(myObj); 

Where MyClass is defined as

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

I hope this helps.

like image 199
Pete Garafano Avatar answered Oct 21 '22 00:10

Pete Garafano