MongoDB序列化约定ignoreifnullconvention忽略错误值

时间:2017-10-16 20:15:43

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

我有一个C#应用程序,它将值写入mongo。有了它,我有一个约定包

var pack = new ConventionPack();
            pack.Add(new IgnoreIfDefaultConvention(true));
            ConventionRegistry.Register(
                "Ignore if default",
                pack,
                t => x);

写入我的数据库是:

var user = new UserModel{
     Name = "Willy",
     Active = false
}
mongoContext.User.InsertOne(user);

我使用它来忽略缺失值并避免在POCO模型中写入每个字段。其中一个值 Active 必须同时包含true和false。但是当我使用Convention包写入值时,它会忽略所有 Active ,这些都是false。
为了测试它,我运行它没有约定包并写入值很好,但使用约定包它没有。有没有办法排除特定字段或告诉约定包接受错误值?
谢谢

1 个答案:

答案 0 :(得分:1)

IgnoreIfDefaultConvention将忽略所有默认值。 请改用IgnoreIfNullConvention。

var pack = new ConventionPack();
pack.Add(new IgnoreIfNullConvention(true));
ConventionRegistry.Register("Ignore if null",pack,t => x);

另一种选择是将UserModel更改为使用枚举而不是布尔标志。例如,枚举UserStatus {Unknown,Active,Inactive}。在这种情况下,IgnoreIfDefault约定将忽略默认值" Unknown"但其余的值将被捕获。