What role does recursive hierarchies play in Entity Framework? Include() seems to be incompatible with it.

c# entity-framework visual-studio-2008

Question

I've got anItem . Item has aCategory .

Category has ID , Name as well as Children.Parent and Children are ofCategory too.

When I do a LINQ to Entities search for a certainItem it doesn't return the associated data.Category even if I use theInclude("Category") method. However, it does not include the whole category, including its parent and children. I am capable.Include("Category.Parent") but this object resembles a tree; it has a recursive structure, and I'm not sure how far it will go.

How can I get EF to completely load theCategory the parent with their parent and children, and so on, with parent and children?

For performance reasons, this is just something that would be required for one particular object, the Category, and not for the whole program.

1
71
11/2/2015 11:38:32 PM

Accepted Answer

Rather of employing theInclude technique you could chooseLoad .

The children's children may then be loaded by doing a for each and looping through all the children. Do a favor for each, then for their offspring, and so on.

The amount of for each loops you have will have the number of levels down hard programmed in.

Here is an instance of usingLoad : 26-26-zzz

23
2/27/2017 9:08:27 AM

Popular Answer

If you are certain that you want the whole hierarchy loaded, I would suggest designing a stored procedure whose purpose is to return every item in a hierarchy while returning the initial object you request (and its children subsequently).

After then, let the EF's relationship maintenance make sure that everyone is connected.

For example, consider:

// the GetCategoryAndHierarchyById method is an enum
Category c = ctx.GetCategoryAndHierarchyById(1).ToList().First();

If your stored method is properly constructed, materializing every object in the hierarchy (i.e.ToList() ) ought to trigger EF relationship fixup.

After that, all of the children of the item you want (First()), as well as the children of those children, should be loaded. No MARS issues either since everything would be filled in from that one stored procedure call.

Hope this is useful.

Alex



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow