c# - 如何为 MongoDb 命名空间中的所有类注册类映射?

标签 c# mongodb mongodb-.net-driver

MongoDB driver tutorial建议通过

将类映射注册到自动映射
BsonClassMap.RegisterClassMap<MyClass>();

我想自动映射给定命名空间的所有类,而无需为每个类显式写下 RegisterClassMap。目前可以吗?

最佳答案

你不需要写 BsonClassMap.RegisterClassMap<MyClass>(); ,因为默认情况下所有类都会自动映射。

您应该使用 RegisterClassMap当您需要自定义序列化时:

 BsonClassMap.RegisterClassMap<MyClass>(cm => {
        cm.AutoMap();
        cm.SetIdMember(cm.GetMemberMap(c => c.SomeProperty));
    });

您还可以使用属性来创建管理序列化(对我来说它看起来更原生):

[BsonId] // mark property as _id
[BsonElement("SomeAnotherName", Order = 1)] //set property name , order
[BsonIgnoreExtraElements] // ignore extra elements during deserialization
[BsonIgnore] // ignore property on insert

您还可以创建在自动映射期间使用的全局规则,例如:

var myConventions = new ConventionProfile();
myConventions.SetIdMemberConvention(new NoDefaultPropertyIdConvention());
BsonClassMap.RegisterConventions(myConventions, t => true);

我只使用属性和约定来管理序列化过程。

希望对您有所帮助。

关于c# - 如何为 MongoDb 命名空间中的所有类注册类映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5505591/

相关文章:

c# - 如何在数组.NET驱动程序中的项目属性上创建MongoDB MultiKey索引

c# - 如何使用 C# 在 Selenium 中处理 firefox 的另存为对话框?

C#:根据平台访问 32 位/64 位 DLL

c# - 如何编写 Null 或 Empty 合并运算符

node.js - 通过 Node JS 插入时,Mongo shell 不显示集合(命令 show collections)

javascript - 如何用更少的行数快速制作多个嵌套属性对象?

linux - 无法使用 pip 下载 mongo-connector

c# - C# 中使用 MD5 和 SHA256 的 CryptoJS AES 加密未生成正确的值

c# - Mongo C# 驱动程序 2.0 - 在不获取文档的情况下查找计数

c# - 我是否仍应在我的连接字符串中指定 Mongo 的副本集?