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

MongoDB插入C# Customer对象时属性显示异常求助

问题原因分析

这是MongoDB .NET驱动的序列化模式切换导致的:

  1. 当所有属性都是只读(仅get;)时:
    驱动会将类识别为不可变类型,自动匹配公共构造函数的参数与属性名(忽略大小写),序列化那些能通过构造函数初始化的属性。你的Name、Surname、Address对应Customer构造函数的name、surname、address参数,因此会被序列化;而Key没有对应的构造函数参数,所以不会被序列化,数据库中只显示前三个属性。

  2. 当Key改为读写(get; set;)时:
    类中出现了可写属性,驱动切换到POCO序列化模式——默认只序列化带有公共setter的属性。此时只有Key满足条件,其他三个只读属性被忽略,因此数据库中仅显示Key。

解决方案

以下几种方法可以让所有属性正常序列化:

方法1:显式标记需要序列化的属性

给所有属性添加[BsonElement]特性,强制驱动序列化这些属性,无论是否有setter:

public class BaseCustomer
{
    [BsonElement]
    public string Key { get; }
    [BsonElement]
    public string Name { get;  }
    [BsonElement]
    public string Surname { get; }
    [BsonElement]
    public string Address { get; }

    protected BaseCustomer(string name, string surname, string address)
    {
        Name = name;
        Surname = surname;
        Address = address;
        Key = "test";
    }
}

方法2:配置类映射强制使用不可变类型序列化

在应用启动时注册类映射,指定驱动使用构造函数来处理序列化,同时显式映射所有属性:

using MongoDB.Bson.Serialization;

// 注册BaseCustomer的类映射
BsonClassMap.RegisterClassMap<BaseCustomer>(cm =>
{
    cm.AutoMap();
    // 指定使用基类的构造函数(参数类型匹配)
    cm.MapConstructor(typeof(string), typeof(string), typeof(string));
    // 显式映射Key属性
    cm.MapMember(c => c.Key);
});

// 注册Customer的类映射
BsonClassMap.RegisterClassMap<Customer>(cm =>
{
    cm.AutoMap();
    // 指定使用Customer的构造函数
    cm.MapConstructor(typeof(string), typeof(string), typeof(string));
});

方法3:将Key的setter设为私有

如果不想破坏不可变设计,可以把Key的setter改为私有,驱动会继续将类视为不可变类型,同时序列化私有setter的属性:

public class BaseCustomer
{
    public string Key { get; private set; }
    public string Name { get;  }
    public string Surname { get; }
    public string Address { get; }

    protected BaseCustomer(string name, string surname, string address)
    {
        Name = name;
        Surname = surname;
        Address = address;
        Key = "test";
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 17:43:18