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

如何将MongoDB Schema/示例对象自动生成C#实体类?

如何根据MongoDB Schema结构生成对应的C#实体类?

输入的MongoDB Schema结构:

{
 bsonType: "object",
 title: "Movie object",
 required: [ "title", "year", "runtime", "plot", "cast" ],
 properties: {
    title: {
       bsonType: "string",
       description: "'name' must be a string and is required"
    },
    year: {
       bsonType: "int",
       minimum: 2017,
       maximum: 3017,
       description: "'year' must be an integer in [ 2017, 3017 ] and is required"
    },
    runtime: {
       bsonType: "int",
       minimum: 1,       
       description: "'runtime' must be a positive integer and is required"
    },
    plot: {
       bsonType: "string",
       description: "'plot' must be a string and is required"
    },
    cast: {
        bsonType: "array",
        description: "'cast' is an array of strings"
    }
 }
}

生成的C#实体类:

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

[BsonIgnoreExtraElements] 
public class Movie {

    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    [BsonElement("title")]
    public string Title { get; set; } = null!;

    [BsonElement("year")]
    public int Year { get; set; }

    [BsonElement("runtime")]
    public int Runtime { get; set; }

    [BsonElement("plot")]
    [BsonIgnoreIfNull]
    public string Plot { get; set; } = null!;

    [BsonElement("cast")]
    [BsonIgnoreIfNull] 
    public List<string> Cast { get; set; } = null!;
}

关键说明:

  • 引入MongoDB.Bson和MongoDB.Bson.Serialization.Attributes命名空间,这是MongoDB .NET驱动的核心依赖
  • [BsonIgnoreExtraElements]特性用于忽略文档中存在但实体类未定义的字段,避免序列化/反序列化报错
  • [BsonId]和[BsonRepresentation(BsonType.ObjectId)]用于映射MongoDB的默认主键_id,允许用字符串类型存储ObjectId
  • [BsonElement("字段名")]明确指定实体类属性与MongoDB文档字段的映射关系
  • 对于必填字段,使用= null!消除可空引用类型的警告(可根据项目配置调整)
  • 数组类型cast对应C#的List<string>,[BsonIgnoreIfNull]用于处理空数组场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 06:13:01