C# MongoDB对象的序列化/反序列化

C# MongoDB对象的序列化/反序列化,c#,mongodb,serialization,mongodb-.net-driver,bson,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("") .Ge

我有以下课程

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")
            }
        );
编辑

这是数据库中保存的内容:

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

问题在于GenericEntity不是一个数据类,并且有许多您不希望持久化的属性。在这种情况下,您将需要手动映射此项。下面,我将映射真正重要的两个属性,名称和AuthenticationType。然后我将告诉MongoDB驱动程序使用接受这两个参数的构造函数构造GenericEntity

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

保存用户后,它在数据库中是什么样子的?谢谢@CraigWilson,问题已更新。我认为问题在于我们无法重新补充泛型实体的水分。您需要为GenericEntity类注册一个类映射,以持久化重新创建它所需的属性,特别是名称和AuthenticationType。然后,你需要映射一个创建者来构造它。@CraigWilson,你能给我一个示例代码吗。谢谢。@dan好吧,他确实制造了驱动程序。
BsonClassMap.RegisterClassMap<GenericIdentity>(cm =>
{
    cm.MapProperty(c => c.Name);
    cm.MapProperty(c => c.AuthenticationType);
    cm.MapCreator(i => new GenericIdentity(i.Name, i.AuthenticationType));
});