I have a linq-to-sql data layer, with 2 tables in it. “Parent” and “Child”. There’s a relationship between Child and Parent (so parent has many children, etc etc), a parent can also have many parents (when children grow up and themselves become parents).
I want to display this hierarchy out to the user, but I’m not sure how to do this efficiently.
The inefficient approach is to do:
foreach(Parent in db.Parents)
{
output(Parent.Parents)
output(Parent.Children)
}
But, this generates a db round trip twice for every iteration in the loop (eek!!), if it’s a big family, this is going to be REALLY expensive.
Is there a better way? (god I hope so!)
I would suggest eager loading the whole collection you wish to pass to the UI. If the method for generating the parent -> parent collection is recursive (which it seems it might be) then use L2S code to select the items in a recursive manner. This way iterating the final collection of results in the UI is not going to trigger the SQL commands in an inefficient way.
Example:
I dont know if this is the best/shortest/cleanest way to do this, but hopefully you will get the idea.
staticfunctions coz its a console app.Table data:
Output:
(the indented/hyphenated names are the respective parents)
This is the debugger output from the L2S dc
Log:..all of which fired in one go at the
.ToList();line (as expected).I hope this is useful.