I need query LINQ and C# core 3.1 with Include and ThenInclude

c# ef-core-3.0 entity-framework-core linq

Question

I need help with LINQ and c# core 3.1. I need to get data from DB in one query. I have a Customer table which has a relation to the Order table. The Order table has a relation with two tables OrderLine and OrderStatus. How can I get this data in one query? Is this possible? Then the OrderLine table has a relation with the Product table and the OrderStatus table has a relation with the OrderStatus2 table. I posted the image of the DB diagram.

public async Task<Customer> GetData(string id)
{
    return await DB.Customer.Where(x => x.Id.Equals(id))
        .Include(o => o.Order)

        //Here is the problem of how to include these two tables?
        //------------------------------------
        .ThenInclude(g => g.OrderLine)
        .ThenInclude(r => r.OrderStatus)
        //------------------------------------

        .ThenInclude(x => x.Product)
        .ThenInclude(x => x.OrderStatus2)

        .AsNoTracking()
        .FirstOrDefaultAsync();
}

Image of the DB diagram

1
0
4/11/2020 4:41:40 PM

Accepted Answer

The ThenInclude pattern allows you to specify a path from the root to a single leaf, hence in order to specify a path to another leaf, you need to restart the process from the root by using the Include method and repeat that for each leaf.

For your sample it would be like this:

Context.Set<Person>()
    .Include(o => o.ContactDetails).ThenInclude(o => o.Addresses) // ContactDetails.Addresses 
    .Include(o => o.ContactDetails).ThenInclude(o => o.Items) // ContactDetails.Items
    .Include(o => o.ContactDetails).ThenInclude(o => o.Events) // ContactDetails.Events
    ...

Reference: Loading Related Data - Including multiple levels

13
11/22/2019 8:30:07 AM


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