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?
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.
As an alternative to the convention based registration, I needed to register class maps for a large number of Type
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With