MongoDB序列化/反序列化对象

时间:2014-05-13 11:54:15

标签: c# mongodb serialization mongodb-.net-driver bson

我有以下课程。

public class User : System.Security.Principal.IPrincipal
{
    public int _id { get; set; }

    public IIdentity Identity { get; set; }

    public bool IsInRole(string role) { }    
}

我正在尝试使用以下代码将此类的实例保存到MongoDB:

new MongoClient("")
    .GetServer()
    .GetDatabase("")
    .GetCollection("")
        .Save<User>(
            new User 
            {
                _id = 101,
                Identity = new GenericIdentity("uName", "Custom")
            }
        );

保存后,从数据库中检索对象时; Identity.NameIdentity.AuthenticationType的值仍为null

这是由于缺少序列化/反序列化指令吗?

我尝试使用类地图,但问题仍然存在。

BsonClassMap.RegisterClassMap<User>(cm =>
{
    cm.AutoMap();
    cm.MapIdProperty(c => c._id);
    cm.MapProperty(c => c.Identity);
});

修改

这是保存在DB中的内容:

{
    "_id" : 101,
    "Identity" : {
        "_t" : "GenericIdentity",
        "Actor" : null,
        "BootstrapContext" : null,
        "Label" : null
    }
}

1 个答案:

答案 0 :(得分:2)

问题是GenericIdentity不是一个数据类,并且有许多你不想持久存在的属性。在这种情况下,您可能需要手动映射。下面,我将映射实际上重要的两个属性,即Name和AuthenticationType。然后我将告诉MongoDB驱动程序使用带有这两个参数的构造函数构造GenericIdentity。

BsonClassMap.RegisterClassMap<GenericIdentity>(cm =>
{
    cm.MapProperty(c => c.Name);
    cm.MapProperty(c => c.AuthenticationType);
    cm.MapCreator(i => new GenericIdentity(i.Name, i.AuthenticationType));
});
相关问题