Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Filter by grandchildren entities

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?

like image 478
Nicros Avatar asked Jan 15 '23 21:01

Nicros


1 Answers

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.

like image 128
Ladislav Mrnka Avatar answered Jan 29 '23 00:01

Ladislav Mrnka