如何使用BsonClassMap配置ObjectIds数组的表示形式?

时间:2013-01-24 15:44:19

标签: 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);
     });

1 个答案:

答案 0 :(得分:2)

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

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