c# - 如何使用 BsonClassMap 配置 ObjectId 数组的表示形式?

标签 c# .net mongodb serialization bson

考虑以下 C# 类:

public class Role
{
    public string Id { get; set; }
    public IEnumerable<string> Users { get; set; }
}

如何使用 BsonClassMap.RegisterClassMap<Role> 配置用户映射到 MongoDB 中的 ObjectId 数组?我能够配置标量属性 Id 映射到 ObjectId,但无法弄清楚如何对序列(数组)执行相同操作:

BsonClassMap.RegisterClassMap<Role>(m =>
    {
        m.MapIdProperty(r => r.Id).SetRepresentation(BsonType.ObjectId);
        // How do I map r.Users to an array of ObjectId??
        m.MapProperty(r => r.Users);
     });

最佳答案

答案是使用正确初始化的 ArraySerializationOptions 对象调用 SetSerializationOptions:

BsonClassMap.RegisterClassMap<Role>(m =>
    {
        m.MapIdProperty(r => r.Id).SetRepresentation(BsonType.ObjectId);
        m.MapProperty(r => r.Users).SetSerializationOptions(
                new ArraySerializationOptions(new
                        RepresentationSerializationOptions(BsonType.ObjectId)));
     });

关于c# - 如何使用 BsonClassMap 配置 ObjectId 数组的表示形式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14505211/

相关文章:

c# - Win8 : Hiding Toast Notifications

php - 将 MongoId 对象数组转换为字符串数组

.net - 使用...进行实时视频编码?

node.js - Mongoose Pre Command 未按预期工作

mongodb - 如何在spring mongo模板中获取聚合查询的计数

c# - 反序列化错误: value cannot be null. 参数名称:type

c# - 是否可以将 HttpClient 配置为不保存 cookie?

c# - 在不知道 sqlDbType 的情况下将 DBNull.Value 与 SqlParameter 一起使用?

.net - LinqToSql 和 HashBytes

c# - XML 错误 : data at root level is invalid