Entity Framework query to get child items

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

Question

I have order structure as below

Order 1234

  • Category 1

    • Item 111

    • Item 222

  • Category 7

    • Item 444

How can I modify the query below to include all items from order 1234

public List<Items> GetAllOrderItems(int orderId)
{

   var result = (from o in _orderContext.Orders
                 where o.OrderId == orderId
                 select s).toList();
}

List<Items> => Item 111,Item 222, Item 444

1
2
2/27/2019 2:23:06 PM

Accepted Answer

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.

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

Popular Answer

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: http://msdn.microsoft.com/en-us/library/bb738708(v=vs.110).aspx

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).



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