Search code examples
c#mongodb

Ignore null property when deserializing with C# MongoDB driver


I'm using MongoDB C# Driver 3.1.0.

I know how to ignore null properties when serializing by using the IgnoreIfNullConvention, but I'd like to ignore a specific null property when deserializing - is there a way to do this?

Specifically, I'm declaring a property in the class like:

public class X
{
    public ICollection<T> Property { get; set; } = new List<T>();

}

The hope is that Property will never be null. But even with this, if Property already has a null value in MongoDB, the driver is deserializing Property to null and overriding the explicit implementation of new List<T>().

I've tried different versions of this without success:

BsonClassMap.RegisterClassMap<X>(x =>
{
    x.MapField(y => y.Property)
        .SetIsRequired(true)
        .SetDefaultValue(new List<T>());
});

Is there any other way to accomplish this?


Solution

  • In addition to creating a custom serializer, MongoDB C# Driver also supports ISupportInitialize. This can be used to assert that the value is set after deserialization, e.g.:

    class MyDocument : ISupportInitialize
    {
        // ...    
        public ICollection<string> ListProperty { get; set; } = new List<string>();
    
        public void BeginInit()
        {
            // Nothing to do here
        }
    
        public void EndInit()
        {
            ListProperty = ListProperty ?? new List<string>();
        }
    }