Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I specify the constructor to use for MongoDB deserialization without using attributes (C#)

Tags:

c#

mongodb

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...

like image 444
W3Max Avatar asked Sep 15 '25 01:09

W3Max


1 Answers

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);
            }
        }
    }
like image 161
W3Max Avatar answered Sep 17 '25 15:09

W3Max