MongoDB C# IgnoreExtraElements is not applied to nested objects

62 Views Asked by At

There are two classes:

public class A {
   public IEnumerable<B> Items { get; set; }
}

public class B {
   public string A { get; set; }
   public int B { get; set; }
}

There is a class map for the A class:

BsonClassMap.RegisterClassMap<A>(classMap =>
{
    classMap.AutoMap();
    classMap.SetIgnoreExtraElements(true);
});

The problem: if my B object contains more properties in the database than I added to the class, the deserialization will be failed due to uknknown properties. Calling "SetIgnoreExtraElements" doesn't help for nested objects, creating a separate class map for the B class also doesn't work also.

I am aware of Conventions and it solves my issue, but is there a workaround to solve the issue using class mapping only?

1

There are 1 best solutions below

0
dododo On

You should specify SetIgnoreExtraElements for B type too. You can do it in this way:

        BsonClassMap.RegisterClassMap<A>(classMap =>
        {
            classMap.AutoMap();
            classMap.SetIgnoreExtraElements(true);
        });

        BsonClassMap.RegisterClassMap<B>(classMap =>
        {
            classMap.AutoMap();
            classMap.SetIgnoreExtraElements(true);
        });

        var client = new MongoClient();
        var db = client.GetDatabase("d");
        var collectionName = "coll";
        var coll = db.GetCollection<BsonDocument>(collectionName);
        coll.InsertOne(BsonDocument.Parse($"{{ 'Items' : [ {{ 'A' : 'a', 'B1' : 1, C : 'c' }} ] }}"));
        var typed = db.GetCollection<A>(collectionName);
        var result = typed.Find("{}").ToList();
        // result: 1 record