How to registerClassMap for all classes in namespace for MongoDb?

MongoDB tutorial suggests registering class maps for automap through

BsonClassMap.RegisterClassMap<MyClass>(); 

I would like to automate all classes in a given namespace without an explicit RegisterClassMap entry for each class. Is this currently possible?

+7
source share
2 answers

You do not need to write BsonClassMap.RegisterClassMap<MyClass>(); , because by default all classes will be automatically deleted.

You should use RegisterClassMap when you need custom serialization:

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

You can also use attributes to create control serialization (for me this looks more familiar):

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

You can also create global rules that are used in autopilot, for example:

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

I use only attributes and conventions to control the serialization process.

I hope for this help.

+12
source

As an alternative to convention-based registration, I needed to register class maps for a large number of Type with some custom initialization code and did not want to repeat RegisterClassMap<T> for each type.

According to KCD's comment, if you need to explicitly register class maps, if you need to deserialize polymorphic class hierarchies, you can use BsonClassMap.LookupClassMap , which will create a default automatic registration for this type.

However, I had to resort to this hacker in order to perform custom map initialization steps, and, unfortunately, LookupClassMap freezes the map upon exit, which prevents further modification of 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, eg classMap.SetDiscriminator, AutoMap etc BsonClassMap.RegisterClassMap(classMap); 

The above code is adapted from the implementation of BsonClassMap LookupClassMap .

+2
source

All Articles