MongoDB.live, free & fully virtual. Register Now MongoDB.live, free & fully virtual. Register Now

Mapping a type with parameterised constructor [C# Driver v2.10.2]

I work on an application that has been using Mongo to manage objects in production for a number of months. I recently tried to upgrade the MongoDB.Driver to latest version and encountered several errors to do with loading objects from the DB. It seems to be when I have a type with a parameterised constructor, e.g.

public class Address
{
    public string Line1 { get; private set; }
    public string Line2 { get; private set; }
    public string City { get; private set; }
    public string County { get; private set; }
    public string Postcode { get; private set; }
    public string Country { get; private set; }

    public Address(string line1, string line2, string city, string county, string postcode, string country)
    {
        Line1 = line1;
        Line2 = line2;
        City = city;
        County = county;
        Postcode = postcode;
        Country = country;
    }
}

I have not had to do any custom mapping. It all just worked. However, recent versions of the library fail with the message:

“An error occurred while deserializing the Address property of class XXX: No matching creator found.”

Adding a class-map and inspecting the cm after AutoMap() has been call shows that it is registering a creator for the 6-param constructor as expected. However, I still get the error.

BsonClassMap.RegisterClassMap<Address>(cm =>
{
  cm.AutoMap();
});

I’ve also tried explicitly registeing a creator without success:

cm.MapCreator(address => new Address(address.Line1, address.Line2, address.City, address.County, address.Postcode, address.Country));

I have narrowed the problem down to going from v2.10.1 to v2.10.2 of the library, and subsequent versions fail in the same way.

The only way I have found to get around the issue is to create a parameterless constructor or make all the setters public, neither of which I want to do. Not all of the properties are always set - they can be null and are not present in the database when I view the persisted object. However, all the properties have IgnoreIfNull set to true, and as I said previously this worked in the past.

Is this change to behaviour intentional? If so what is the recommended approach to mapping? Any help would be appreciated.

Matt