gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:36:15 26 4
gpt4 key购买 nike

我希望有人可以提供帮助。我开始掌握 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com