Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include() nested child entity in linq

How do I include a child of a child entitiy?

Ie, Jobs have Quotes which have QuoteItems

var job = db.Jobs             .Where(x => x.JobID == id)             .Include(x => x.Quotes)             .Include(x => x.Quotes.QuoteItems) // This doesn't work             .SingleOrDefault(); 

Just to be clearer - I'm trying to retrieve a single Job item, and it's associated Quotes (one to many) and for each Quote the associated QuoteItems (One Quote can have many QuoteItems)

The reason I'm asking is because in my Quote Index view I'm trying to show the Total of all the Quote items for each Quote by SUMming the Subtotal, but it's coming out as 0. I'm calling the Subtotal like this:

@item.QuoteItem.Sum(p => p.Subtotal) 

I believe the reason I have this issue is that my Linq query above isn't retrieving the associated QuoteItems for each Quote.

like image 209
Evonet Avatar asked Jun 09 '14 12:06

Evonet


2 Answers

To get a job and eager load all its quotes and their quoteitems, you write:

var job = db.Jobs         .Include(x => x.Quotes.Select(q => q.QuoteItems))         .Where(x => x.JobID == id)         .SingleOrDefault(); 

You might need SelectMany instead of Select if QuoteItems is a collection too.

Note to others; The strongly typed Include() method is an extension method so you need to include using System.Data.Entity; at the top of your file.

like image 193
Mattias Åslund Avatar answered Sep 23 '22 12:09

Mattias Åslund


This will do the job (given that we are talking entity framework and you want to fetch child-entities):

var job = db.Jobs             .Include(x => x.Quotes) // include the "Job.Quotes" relation and data             .Include("Quotes.QuoteItems") // include the "Job.Quotes.QuoteItems" relation with data             .Where(x => x.JobID == id) // going on the original Job.JobID             .SingleOrDefault(); // fetches the first hit from db. 

For more information about the Include statement have a look at this: https://docs.microsoft.com/en-us/dotnet/api/system.data.objects.objectquery-1.include

This answer has been getting upvotes throught the years, so I'd just like to clarify, try https://stackoverflow.com/a/24120209/691294 first. This answer is for those cases where all else fails and you have to resort to a black magic solution (i.e. using magic strings).

like image 40
flindeberg Avatar answered Sep 23 '22 12:09

flindeberg