4

I would like to SetIgnoreIfDefault(true) for ALL properties of a class. (this can save TONS of default data in the storage)

I can call SetIgnoreIfDefault explicitly for every property:

    BsonClassMap.RegisterClassMap<MyClass>(cm =>
    {
        cm.AutoMap();
        cm.MapProperty(x => x.A).SetIgnoreIfDefault(true);
        cm.MapProperty(x => x.B).SetIgnoreIfDefault(true);
        cm.MapProperty(x => x.C).SetIgnoreIfDefault(true);
        cm.MapProperty(x => x.D).SetIgnoreIfDefault(true);
        cm.MapProperty(x => x.E).SetIgnoreIfDefault(true);
        ...
        cm.SetIgnoreExtraElements(true);
    });

However I have many classes and many properties , and If I modify the classes I need to remember to change the Registration.

Is there is a way to set it for ALL properties of a class in one call?

Is there is a way to set it for ALL properties Globally?

Thanks

Aviko
  • 1,139
  • 12
  • 21

1 Answers1

6

Is there is a way to set it for ALL properties of a class in one call?

Is there is a way to set it for ALL properties Globally?

You could achieve this easily with custom member map convention.

Here is a sample convention that ignores properties with default values for all classes:

public class IgnoreDefaultPropertiesConvention : IMemberMapConvention
{
    public string Name => "Ignore default properties for all classes";

    public void Apply(BsonMemberMap memberMap)
    {
        memberMap.SetIgnoreIfDefault(true);
    }
}

Here is convention for specific class:

public class IgnoreDefaultPropertiesConvention<T> : IMemberMapConvention
{
    public string Name  => $"Ignore Default Properties for {typeof(T)}";

    public void Apply(BsonMemberMap memberMap)
    {
        if (typeof(T) == memberMap.ClassMap.ClassType)
        {
            memberMap.SetIgnoreIfDefault(true);
        }
    }
}

You could register custom convention in the following way (before any requests to MongoDB):

var pack = new ConventionPack
{
    new IgnoreDefaultPropertiesConvention()
};
ConventionRegistry.Register("Custom Conventions", pack, t => true);
CodeFuller
  • 30,317
  • 3
  • 63
  • 79