Note: I'm using the MongoDB C# Driver 2.0
I would like to replicate the behaviour of the BsonConstructor attribute but using the BsonClassMap API.
Something like this:
BsonClassMap.RegisterClassMap<Person>(cm =>
{
cm.AutoMap();
cm.MapCreator(p => new Person(p.FirstName, p.LastName));
});
but without having to specify each argument.
The reason I want to do it this way is that I don't want to "pollute" my domain model with implementation concerns.
I have found this (SetCreator)
BsonClassMap.RegisterClassMap<Person>(cm =>
{
cm.AutoMap();
cm.SetCreator(what goes here?);
});
but I don't know how to use the SetCreator function, and if it does what I think it does...
I achieved the same result using the conventions instead of BsonClassMap
Here is an example (reading (serialization) from read only public properties and writing (deserialization) to the constructor)
public class MongoMappingConvention : IClassMapConvention
{
public string Name
{
get { return "No use for a name"; }
}
public void Apply(BsonClassMap classMap)
{
var nonPublicCtors = classMap.ClassType.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance);
var longestCtor = nonPublicCtors.OrderByDescending(ctor => ctor.GetParameters().Length).FirstOrDefault();
classMap.MapConstructor(longestCtor);
var publicProperties = classMap.ClassType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.CanRead);
foreach (var publicProperty in publicProperties)
{
classMap.MapMember(publicProperty);
}
}
}
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