Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading