How to get a reference to a parent in a deserialized MongoDB document?

Hope someone can help. I am going to deal with the C # driver for MongoDB and how it handles serialization. Consider the following class examples:

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

Note that SubThing has a property that refers to the parent. Therefore, when creating objects, I do like this:

  Thing T = new Thing(); T.ThingName = "My thing"; SubThing ST = new SubThing(); ST.SubThingName = "My Subthing"; T.ST = ST; ST.ParentThing = T; 

The ParentThing property is set to BsonIgnore, because otherwise it will cause a circular reference when serialized in MongoDB.

When I do serialization in MongoDB, it creates the document exactly as I expect:

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

Here's the problem: when I deserialize, I lose the SubThing link to her parent. Is there a way to set up deserialization so that the ParentThing property is always its parent document?

+5
source share
2 answers

from mongodb website

Implementing ISupportInitialize - The driver respects an entity that implements ISupportInitialize, which contains 2 methods: BeginInit and EndInit. This method is called before deserialization and after its completion. It is useful for performing operations before or after deserialization, such as processing circuit changes, pre-computes some expensive operations.

therefore, Thing will implement ISupportInitialize , and the BeginInit function will remain empty, and Endinit will contain St.ParentThing = this;

+5
source

At this level of abstraction, it is difficult to give a definite answer.

One way is for the class to implement ISupportInitialize , which offers a hook after de-serialization. This is probably the easiest solution to the problem. Otherwise, the same link also shows how to write a custom serializer, but in this case it is not required.

+1
source

Source: https://habr.com/ru/post/1213755/


All Articles