【问题标题】:Mongodb C# driver ignore Null and Empty Lists (ToBsonDocument)Mongodb C# 驱动程序忽略 Null 和空列表 (ToBsonDocument)
【发布时间】:2021-07-16 16:18:35
【问题描述】:
ConventionRegistry.Register("IgnoreIfDefault", 
                            new ConventionPack { new IgnoreIfDefaultConvention(true) }, 
                            _ => true);

var bsonDocument = anon.ToBsonDocument();

使用 IgnoreIfDefaultConvention 可能会导致意外行为,因为它会影响所有默认值。例如,下面列出的值将不会被保存:

int = 0
decimal = 0
bool = false

如果我只想忽略 空值和空数组,最好的方法是什么?

【问题讨论】:

    标签: c# mongodb mongodb-.net-driver bson


    【解决方案1】:

    我自己没有使用它,但我认为答案是这个约定:IgnoreIfNullConvention。您也可以为特定字段配置特定约定:

    BsonClassMap.RegisterClassMap<test>(c => c.MapField(e => e.A).SetIgnoreIfNull(ignoreIfNull: true));
    

    或者使用这个属性BsonIgnoreIfNullAttribute

    更新: 如果你需要更复杂的约定,你总是可以实现一个自定义的:https://mongodb.github.io/mongo-csharp-driver/2.12/reference/bson/mapping/conventions/

    【讨论】:

    • 感谢您的回复。我没有单独的类,这就是为什么我不能使用属性和 RegisterClassMap。目标是将动态或匿名对象转换为 BsonDocument 也排除 null 和空列表。
    • IgnoreIfNullConvention 不会忽略空列表
    • doesn't ignore empty lists 因为它不为空?如果你需要更复杂的约定,你总是可以实现一个自定义的:mongodb.github.io/mongo-csharp-driver/2.12/reference/bson/…
    • 看起来这就是我需要的Custom Conventions。我将尝试编写自己的自定义约定。只需像上一条评论一样更新您的答案(如果您愿意),我会接受的。如果不是,我稍后会发布自定义约定。谢谢
    猜你喜欢
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 2022-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多