Search code examples
mongodbmongodb-.net-driver

MongDb C# Driver is deserialzing null values for a List member as empty


I'm using MongoDB with c# driver in one of the applications. I have defined an entity as below and also defined classmaps to enforce a schema.

public class TestEntity
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public List<SomeModel> Properties { get; set; }
}

Also, I've defined conventions to disable serialization of empty or null arrays/lists.

new ConventionPack { new IgnoreIfNullConvention(true)
conventionPack.Add(new IgnoreEmptyArraysConvention());

Everything works as expected, but when I query the document back using c# driver like below, I get the Properties as an empty list instead of null.

Database.GetCollection<TestEntity>("test").Find(filter, findOptions).FirstOrDefault()

For example, if I have a testentity document as follows, when I query using c# driver "Properties" property is returned as empty list instead of null.

{ "_id":ObjectId("5991be3475f14655406cd301"), "name": "test", "description": "test" }

I couldn't find an answer when I searched online. Hope someone can help. Thanks


Solution

  • Remove the convention IgnoreEmptyArraysConvention looking at the code here it seems that it creates a new instance of a list.