EF4 querying from parent to grandchildren

Posted by Hans Kesting on Stack Overflow See other posts from Stack Overflow or by Hans Kesting
Published on 2010-06-16T09:26:47Z Indexed on 2010/06/17 7:23 UTC
Read the original article Hit count: 663

Filed under:

I have a model withs Parents, Children and Grandchildren, in a many-to-many relationship. Using this article I created POCO classes that work fine, except for one thing I can't yet figure out.

When I query the Parents or Children directly using LINQ, the SQL reflects the LINQ query (a .Count() executes a COUNT in the database and so on) - fine. The Parent class has a Children property, to access it's children. But (and now for the problem) this doesn't expose an IQueryable interface but an ICollection. So when I access the Children property on a particular parent all the Parent's Children are read. Even worse, when I access the Grandchildren (theParent.Children.SelectMany(child => child.GrandChildren).Count()) then for each and every child a separate request is issued to select all data of it's grandchildren. That's a lot of separate queries!

Changing the type of the Children property from ICollection to IQueryable doesn't solve this. Apart from missing methods I need, like Add() and Remove(), EF just doesn't recognize the navigation property then.

Are there correct ways (as in: low database interaction) of querying through children (and what are they)? Or is this just not possible?

© Stack Overflow or respective owner

Related posts about entity-framework-4