Search code examples
c#entity-framework-coreef-core-8.0

EF Core: Get list from child entities included with .ThenInclude


I use EF Core 8 to model my database. I want to get a list of tenants which can be accessed by a user. Therefore I use the following query:

var x = dbContext.Users
    .Where(u => u.IdentityId == "089ebd4e-8fe0-48ce-93cd-c8c9ead5de9f")
    .Include(u => u.Users2Groups)
    .ThenInclude(u2G => u2G.Group)
    .ThenInclude(g => g.Tenants2Groups)
    .ThenInclude(t2G => t2G.Tenant)
    .Distinct();

I tried to use

var y = x.Select(u => u.Users2Groups.Select(u2G => u2G.Group.Tenants2Groups.Select(t2G => t2G.Tenant))).ToList();

But that doesn't give me a list of the tenants. How can I get the list of the tenants?


Solution

  • It should be selected via SelectMany. I prefer to use Query syntax when there is more than one table in query.

    var query = 
        from u in dbContext.Users
        where u.IdentityId == "089ebd4e-8fe0-48ce-93cd-c8c9ead5de9f"
        from u2g in u.Users2Groups
        from t2g in u2g.Group.Tenants2Groups
        select t2g.Tenent;
    
    query = query.Distinct();
    

    Includes are not needed for such query.