gpt4 book ai didi

c# - MongoDB c# 驱动程序 : How to set SetIgnoreIfDefault for all members in a class

转载 作者:可可西里 更新时间:2023-11-01 10:00:03 25 4
gpt4 key购买 nike

我想为类的所有属性设置 IgnoreIfDefault(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);
});

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

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

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

谢谢

最佳答案

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 轻松实现此目的.

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

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

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

这里是特定类的约定:

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);

关于c# - MongoDB c# 驱动程序 : How to set SetIgnoreIfDefault for all members in a class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49389531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com