You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用MongoDB C# Driver反序列化时忽略null属性的方法

反序列化时忽略MongoDB中的null值,保留集合初始化值

针对MongoDB C# Driver 3.1.0的场景:当数据库中集合属性存储为null时,反序列化会覆盖类中显式初始化的new List<T>(),以下两种方法可以解决这个问题:

方法一:自定义序列化器处理null值

编写一个能在反序列化时拦截null并返回空集合的序列化器,然后绑定到目标属性:

首先实现序列化器:

public class NullSafeListSerializer<T> : EnumerableSerializerBase<List<T>, T>
{
    public NullSafeListSerializer() : base(new ListSerializer<T>()) { }

    public override List<T> Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        var currentType = context.Reader.GetCurrentBsonType();
        if (currentType == BsonType.Null)
        {
            context.Reader.ReadNull();
            return new List<T>();
        }
        return base.Deserialize(context, args);
    }
}

然后在类映射中注册:

BsonClassMap.RegisterClassMap<X>(cm =>
{
    cm.AutoMap();
    cm.MapMember(x => x.Property)
        .SetSerializer(new NullSafeListSerializer<T>());
});

方法二:反序列化后回调修复null值

通过PostDeserializationCallback在反序列化完成后检查属性,若为null则重新赋值为空集合:

BsonClassMap.RegisterClassMap<X>(cm =>
{
    cm.AutoMap();
    cm.PostDeserializationCallback = obj =>
    {
        var xInstance = obj as X;
        if (xInstance?.Property == null)
        {
            xInstance.Property = new List<T>();
        }
    };
});

原方法无效的原因

你之前用的SetIsRequired(true)仅要求文档必须包含该字段,字段为null时不会处理;SetDefaultValue(new List<T>())只在字段不存在时生效,当字段存在但为null时,驱动仍会将null赋值给属性,因此无法达到预期效果。

内容的提问来源于stack exchange,提问作者crgolden

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 01:30:06