c# - 如何在反序列化的 MongoDB 文档中获取对父对象的引用?

标签 c# mongodb deserialization

我希望有人可以提供帮助。我开始掌握 MongoDB 的 C# 驱动程序以及它如何处理序列化。考虑以下示例类:

class Thing
{
    [BsonId]
    public Guid Thing_ID { get; set; }
    public string ThingName {get; set; }
    public SubThing ST { get; set; }

    public Thing()
    {
        Thing_ID = Guid.NewGuid();
    }
}

class SubThing
{
    [BsonId]
    public Guid SubThing_ID { get; set; }
    public string SubThingName { get; set; }
    [BsonIgnore]
    public Thing ParentThing { get; set; }

    public SubThing()
    {
        SubThing_ID = Guid.NewGuid();
    }
}

请注意,SubThing 有一个引用其父级的属性。因此,在创建对象时,我会这样做:

        Thing T = new Thing();
        T.ThingName = "My thing";

        SubThing ST = new SubThing();
        ST.SubThingName = "My Subthing";

        T.ST = ST;
        ST.ParentThing = T;

ParentThing 属性设置为 BsonIgnore,否则在序列化到 MongoDB 时会导致循环引用。

当我对 MongoDB 进行序列化时,它会完全按照我的预期创建文档:

{
"_id" : LUUID("9d78bc5c-2abd-cb47-9478-012f9234e083"),
"ThingName" : "My thing",
"ST" : {
    "_id" : LUUID("656f17ce-c066-854d-82fd-0b7249c80ef0"),
    "SubThingName" : "My Subthing"
}

问题是:当我反序列化时,我失去了 SubThing 对其父级的引用。有没有办法配置反序列化,让 ParentThing 属性始终是它的父文档?

最佳答案

来自 mongodb 网站

Implementing ISupportInitialize - The driver respects an entity implementing ISupportInitialize which contains 2 methods, BeginInit and EndInit. These method are called before deserialization begins and after it is complete. It is useful for running operations before or after deserialization such as handling schema changes are pre-calculating some expensive operations.

所以,Thing 将实现 ISupportInitialize 并且函数 BeginInit 将保持为空,而 Endinit 将包含 St.ParentThing = this;

关于c# - 如何在反序列化的 MongoDB 文档中获取对父对象的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28615545/

相关文章:

c# - 使用 XDocument 写入 XML,但知道在何处写入

具有默认大小或提供一个的 C# 通用列表

mongodb - 在双重嵌套数组中查找

android - IllegalAccessException - 从不可序列化继承的对象的序列化

java - Jackson 反序列化空数组失败

c# - EPPlus LoadFromDataTable 错误

c# - 发布新版 ASP.NET 网站 - 最佳实践

javascript - 如何将排序操作后的序列号插入到mongoDB中?

javascript - 为什么node express中的mongodb无法将结果设置为外部变量

java - Java 9计划的 "Filtering Incoming Serialization Data"是否解决了数据反序列化安全漏洞?