Search code examples
c#mongodbmongodb-.net-driver

How to RegisterClassMap for all classes in a namespace for MongoDb?


The MongoDB driver tutorial suggests to register class maps to automap via

BsonClassMap.RegisterClassMap<MyClass>();

I would like to automap all classes of a given namespace without explicitly writing down RegisterClassMap for each class. Is this currently possible?


Solution

  • You don't need write BsonClassMap.RegisterClassMap<MyClass>();, because all classes will be automapped by default.

    You should use RegisterClassMap when you need custom serialization:

     BsonClassMap.RegisterClassMap<MyClass>(cm => {
            cm.AutoMap();
            cm.SetIdMember(cm.GetMemberMap(c => c.SomeProperty));
        });
    

    Also you can use attributes to create manage serialization(it's looks like more native for me):

    [BsonId] // mark property as _id
    [BsonElement("SomeAnotherName", Order = 1)] //set property name , order
    [BsonIgnoreExtraElements] // ignore extra elements during deserialization
    [BsonIgnore] // ignore property on insert
    

    Also you can create global rules thats used during automapping, like this one:

    var myConventions = new ConventionProfile();
    myConventions.SetIdMemberConvention(new NoDefaultPropertyIdConvention());
    BsonClassMap.RegisterConventions(myConventions, t => true);
    

    I am using only attributes and conventions to manage serialization process.

    Hope this help.