Serialization in Mongo Database using c#.

Serialization is the process of mapping an object to a BSON document that can be saved in MongoDB, and deserialization is the reverse process of reconstructing an object from a BSON document. For that reason the serialization process is also often referred to as "Object Mapping."


Serialization is handled by the BSON Library .


Creating a class map


To create a class map in your intialization code write:

    BsonClassMap.RegisterClassMap<testClass>();

If you want to control the creation of the class map you can provide your own initialization code in the form of a lambda expression:

    BsonClassMap.RegisterClassMap<testClass)(cm => {
        cm.MapProperty(c => c.SomeProperty);
        cm.MapProperty(c => c.AnotherProperty);
    });

When automapping a class there are a lot of decisions that need to be made. For example:

  • Which fields or properties of the class should be serialized

  • Which field or property of the class is the "Id"

  • What element name should be used in the BSON document

Ebook Download
View all
Learn
View all