MongoDB.live, free & fully virtual. Register Now MongoDB.live, free & fully virtual. Register Now

Add reference to parent object (deserialize)

Hi,

I am searching for a way how to initialize my objects and refer to the parent object.

As an example, this is how the (simplified) document is stored

{
  Id: "366230c4-2773-4891-b397-4cfe19206181",
  Entities: [
    {
     Id: "8303acc4-412f-4540-9b47-e3be0d7b925a",
     Name: "some value"
    }
  ]
}

In C# I deserialize this object into these 2 classes.

public class ParentEntity {
  public Guid Id {get; private set;}
  public List<ChildEntity> Entities { get;  private set; }
}

public class ChildEntity {
  public Guid Id {get; private set;}
  public ParentEntity Parent {get; private set;}

  public ChildEntity() {}

  public ChildEntity( ParentEntity parent, Guid id) {
   Parent = parent;
   Id = id;
  }
}

The ChildEntity class contains a reference to the Parent class that needs to be initialized somehow.

I did not find a way how to do this through the BsonClassMap by setting one of the create/factory methods. Is there a clean way to call the constructor and have a reference to the parent class ParentEntity. My goal is to avoid changing my domain objects.

I found a way by implementing the ISupportInitialize interface of the ParentEntity and set the parent in the EndInit method, by exposing an internal method. But this involves changing the domain model that I try to avoid.

public class ParentEntity : ISupportInitialize {

  ///....
  public void EndInit()
  {
    entities.ForEach(e => e.SetParent(this));
   }
}

public class ChildEntity {
//.....
 internal SetParent(ParentEntity parent) {
  Parent = parent;
 }
}

I’m looking for a factory solution that helps me build my models during deserialization. Please let me know if anyone knows a smart solution.