WYSIWYG

http://kufli.blogspot.com
http://github.com/karthik20522

Wednesday, February 15, 2012

MongoCSharp - Custom Serializer

As part of MongoDB Csharp driver is the custom serialization property, IbsonSerializable. The idea behind the use of this is to create a custom seralizer and deserializer to add and access documents. But as always the documentation is quite off and hard to find any information about this. Following is an example of using bson serializer:

Let’s say that we want to build a class that has a “LogDate” property of type DateTime but we want to save this property into MongoDB as “CreateDate” alias and of type System.Int64.



In the Serialize function, an anonymouse class is created where CreateDate is the new field Name and with value to be long (DateTime.Ticks). This anonymouse class is then converted into a BsonDocument and sent into the writer.

In the Deserialize function, the data from MongoDb is read from the reader and converted into a DemoClass object. CreateDate is read from the reader and converted into logDate format of DateTime.

Labels: