c# - MongoCollectionSettings.GuidRepresentation 已过时,有什么替代方法?

标签 c# mongodb mongodb-.net-driver

我正在使用 MongoDB.Driver 2.11.0 和 .Net Standard 2.1。为了确保数据库存在并且集合存在,我有以下代码:

IMongoClient client = ...; // inject a Mongo client

MongoDatabaseSettings dbSettings = new MongoDatabaseSettings();
IMongoDatabase db = client.GetDatabase("MyDatabase", dbSettings);

MongoCollectionSettings collectionSettings = new MongoCollectionSettings()
{
    GuidRepresentation = GuidRepresentation.Standard,
};
IMongoCollection<MyClass> collection = db.GetCollection<MyClass>("MyClasses", collectionSettings);
在 MongoDB.Driver 的早期版本中,此代码将在没有任何警告的情况下编译。在 v2.11.0 中,我现在收到一条警告,指出“MongoCollectionSettings.GuidRepresentation 已过时:改为配置序列化程序”,但我找不到任何示例来说明设置 Guid 序列化格式的新方法。有谁知道为集合设置序列化程序的其他方法?

最佳答案

如果要为特定属性定义 GuidRepresentation,可以在类映射的注册过程中进行,如下所示:

BsonClassMap.RegisterClassMap<MyClass>(m =>
{
    m.AutoMap();
    m.MapIdMember(d => d.Id).SetSerializer(new GuidSerializer(GuidRepresentation.Standard));
});
如果你想在全局范围内做到这一点:
BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));

关于c# - MongoCollectionSettings.GuidRepresentation 已过时,有什么替代方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63264362/

相关文章:

c# - 在 MVC 4 中返回下载在 Android 上不起作用

c# - 有 "Post deserialization hook"吗?

c# - 派生属性?

c# - 我应该在 XNA 中重用模型实例吗?

c# - 包含对面的实体 EF6

node.js - Mongoose 无法使用字符串类型进行填充

javascript - 如何使用 SailsJS 和 MongoDB 在生产模式下迁移模型

node.js - 蒙古客户端 : how to set a value of an embedded document

c# - 如何在 Mongo 集合中查找最新文档 (C#)

c# - 在 MongoDb + C# 中反序列化没有默认构造函数的对象