© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
9 replies
Ole (ping please)

❔ Selecting child tables using EF Core

I have the following class hierarchy
Enterprise => Company => Site => Department => Container
What would be the most efficent way of selecting a container with a given ID using ef core. In my DbContext I only have a reference to the root object, Enterprise

Currently I have this mess:
return await _dbContext.Enterprise
    .AsNoTracking()
    .Include(x => x.Companies)
        .ThenInclude(x => x.Sites)
        .ThenInclude(x => x.Departments)
        .ThenInclude(x => x.Containers)
    .SelectMany(x => x.Companies)
    .SelectMany(x => x.Sites)
    .SelectMany(x => x.Departments)
    .SelectMany(x => x.Containers)
    .FirstOrDefaultAsync(x => x.Id == id);
return await _dbContext.Enterprise
    .AsNoTracking()
    .Include(x => x.Companies)
        .ThenInclude(x => x.Sites)
        .ThenInclude(x => x.Departments)
        .ThenInclude(x => x.Containers)
    .SelectMany(x => x.Companies)
    .SelectMany(x => x.Sites)
    .SelectMany(x => x.Departments)
    .SelectMany(x => x.Containers)
    .FirstOrDefaultAsync(x => x.Id == id);
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Include child of nullable in EF Core
C#CC# / help
3y ago
✅ EF Core Junction Tables with seperate columns
C#CC# / help
15mo ago
EF Core
C#CC# / help
2y ago
Ef core help
C#CC# / help
10mo ago