开发者

How to load instances in a hierarchy with circular references just once?

I have a object structure like this:

public class Entity
{
    IList<Relationship> Relationships{get;set;}
}

public class Relationship
{
    public Relationship(Entity parent, IList<Entity> children)
    {
    //set properties
    }
    Entity Parent{get;private set;}
    IList<Entity> Children{get;private set;}
}

The Relationship contains all information about the parent and child instances, and I would like to share the same Relationship instance on the parent and all child instances that make up the relationship.

Now when I come to load my entities from the db I start with the top entity, which then loads the relatio开发者_StackOverflow社区nships. I thought I could just cache the relationship I am building and reuse the same instance for the children. But this doesn't work as to create a relationship I need to load all child entities, so each child entity tries to recreate the same relationship I am currently trying to get the children for before it has been created, so I end up creating all of the relationship instances below me in the tree before I can add the relationship to the cache.

Is there a way I can get round this without making the children a settable property of my relationship, so I can create the reference to the relationship before the children are created?


So I managed this by introducing a RelationshipBuilder class which I used to keep track of the parents and children of a relationship without actually creating it.

This enabled me to load an entity and create its relationships in the builder, when the relationships tried to create the children they checked with the builder to see that the relationship was already being created and returned.

This meant I could navigate all the way down the hierarchy loading all of the entity instance and setting the parent entity and child entities associated with the relationships. Once all of the entities had been loaded and the recursion had completed and we were returned to the entry point where we started loading the entities I ask the relationship builder to resolve all the relationships. This then creates each relationship it has been informed about and sets the relationship instance on the parent and child instances which are involved in that relationship.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜