If I have the following tables:
Parent
: has ParentId
Child
: has ChildId
and ParentId
Grandchild
: has GrandchildId
, ChildId
and Quantity
Whats the best approach to retrieve a list of Parents where they have a grandchild with quantity greater than 10 (for example)?
I played with linq to entity, generating something like:
context.Parent.Includes("Children").Include("GrandChildren").Where( ... )
But wasn't sure about the syntax, and I wonder about performance- do the includes load up all objects? What's the best way to accomplish this?
Try this:
var query = context.Parents
.Where(p => p.Children.Any(
c => c.GrandChildren.Any(g => g.Quantity > 10));
Include
will indeed load all child and grandchild entities related to loaded parents.
The performance is bad with this approach...
context.Parent.Includes("Children").Include("Children.GrandChildren").Where( ... )
If you need the children and grandchildren at a later point or maybe don't need them at all, try to load them later with:
if (!parent1.ChildrenReference.IsLoaded)
parent1.ChildrenReference.Load();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.