Entity Framework query to get child items

c# entity-framework entity-framework-6 linq-to-entities

Accepted Answer

To obtain a position and eagerly load each of its quotes and quoteitems, you type:

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

You could requireSelectMany in place ofSelect whether QuoteItems is also a collection.

Observation for others: The boldfacedInclude() since method is an extension method, you mustusing System.Data.Entity; in the file's header.

46
2/7/2019 2:44:09 AM

Popular Answer

Given that we are talking about an entity framework and you wish to fetch child entities, the following will work:

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 additional details regarding theInclude look at this statement: http://msdn.microsoft.com/en-us/library/bb738708(v=vs.110).aspx

Try https://stackoverflow.com/a/24120209/691294 first, as this answer has received many upvotes throughout the years. I just wanted to make that clear. This remedy is for situations where all else has failed and you must turn to a black magic fix (i.e. using magic strings).



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow