0

Let's say I have two simple entities:

class Cat
{
    int Id;
    string Name;
    ICollection<CatRelation> ToRelations;
    ICollection<CatRelation> FromRelations;
}
class CatRelation
{
    int FromCatId;
    int ToCatId;
    Cat FromCat;
    Cat ToCat;
    string RelationType;
}

What I would like to do is load all the Cats and their relations, and have the navigation properties work throughout the whole graph. So far I have something like this:

context.Cats.Include(cat => cat.ToRelations)
            .Include(cat => cat.FromRelations)
            .ToList()

After this the context is disposed of. Further down the line the list is iterated through. This works fine for getting to the relations -entities, but if I, for example, iterate over the Cats and then try to iterate over all their relations, the other end of the CatRelation is there, but its navigation properties won't work (ContextDisposed). As in, given the following cat var cat1 = cats.First().ToRelations.First().ToCat, if I try to access cat1.ToRelations, I get a ContextDisposed -exception.

So is there a way for me to ask the context to fix all these navigation properties (because I know I have loaded all the Cats of all the CatRelations), before disposing of the context?

bobblez
  • 1,340
  • 20
  • 35
  • I think this is a duplicate of this question . https://stackoverflow.com/questions/10822656/entity-framework-include-multiple-levels-of-properties – Derek Strickland Jun 02 '15 at 13:07
  • Can you give a full code example demonstrating what you are doing? I see no reason why you shouldn't be able to achieve this. – user2697817 Jun 02 '15 at 15:45

1 Answers1

0

For a graph I think it would be better to load the entire table, then construct the graph yourself. Even if you could get EF to recursively pull all of the data from the database, it wouldn't reuse the existing objects for relations (if they exist in memory) but rather construct new instances with the same data. That's likely not what you want and it would result in a lot more data being transferred to boot.

In any event I don't think it's possible to get EF to pull data that is nested arbitrarily deep or might have cycles in their relationship graph.

tvanfosson
  • 524,688
  • 99
  • 697
  • 795