Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 268
tobsen Avatar asked Mar 31 '11 19:03

tobsen


2 Answers

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.

like image 96
Andrew Orsich Avatar answered Sep 22 '22 00:09

Andrew Orsich


As an alternative to the convention based registration, I needed to register class maps for a large number of Types with some custom initialization code, and didn't want to repeat RegisterClassMap<T> for each type.

As per KCD's comment, if you do need to explicitly register class maps if you need to deserialize polymorphic class hierarchies, you can use BsonClassMap.LookupClassMap which will create a default AutoMapped registration for a given Type.

However, I needed to resort to this hack in order to perform custom map initialization steps, and unfortunately LookupClassMap freezes the map upon exit, which prevents further change to the returned BsonClassMap:

var type = typeof(MyClass);

var classMapDefinition = typeof(BsonClassMap<>);
var classMapType = classMapDefinition.MakeGenericType(type);
var classMap = (BsonClassMap)Activator.CreateInstance(classMapType);

// Do custom initialization here, e.g. classMap.SetDiscriminator, AutoMap etc

BsonClassMap.RegisterClassMap(classMap);

The code above is adapted from the BsonClassMap LookupClassMap implementation.

like image 31
StuartLC Avatar answered Sep 21 '22 00:09

StuartLC