【问题标题】:MongoDB Serialisation/Deserialisation of objectsMongoDB反序列化/对象的反序列化
【发布时间】:2014-05-14 01:08:25
【问题描述】:

我有以下课程。

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);
});

编辑

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

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

【问题讨论】:

  • 保存用户后,它在数据库中是什么样子的?
  • 感谢@CraigWilson,问题已更新。
  • 我认为问题在于我们无法为 GenericIdentity 重新补水。您需要为 GenericIdentity 类注册一个类映射,以保留重新创建它所需的属性,特别是 Name 和 AuthenticationType。然后,您需要映射一个 Creator 来构造它。
  • @CraigWilson,你能给我一个示例代码吗?谢谢。

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


【解决方案1】:

问题在于 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));
});

【讨论】:

  • @dan 好吧,他确实构建了驱动程序。
猜你喜欢
  • 1970-01-01
  • 2012-04-15
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
  • 2017-08-02
  • 1970-01-01
  • 2013-02-22
  • 2016-10-14
相关资源
最近更新 更多