MongoDB c# 驱动程序:如何为 class 中的所有成员设置 SetIgnoreIfDefault

MongoDB c# Driver: How to set SetIgnoreIfDefault for all members in a class

我想为 class 的所有属性设置 SetIgnoreIfDefault(true)。 (这可以在存储中保存 TONS 的默认数据)

我可以为每个 属性:

显式调用 SetIgnoreIfDefault
    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);
    });

但是我有很多 classes 和很多属性,如果我修改 classes 我需要记得更改注册。

有没有办法在一次调用中为 class 的所有属性设置它?

有没有办法在全局范围内为所有属性设置它?

谢谢

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?

您可以使用 custom member map convention 轻松实现此目的。

这是一个示例约定,它忽略所有 classes 具有默认值的属性:

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

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

这是特定的约定 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);
        }
    }
}

您可以通过以下方式注册自定义约定(在向 MongoDB 发出任何请求之前):

var pack = new ConventionPack
{
    new IgnoreDefaultPropertiesConvention()
};
ConventionRegistry.Register("Custom Conventions", pack, t => true);