❔ 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);
8 Replies
Pobiega
Pobiega2y ago
If you only want the container, why start from enterprises? Go directly for container.
Ole (ping please)
The dbContext only has the enterprise attribute. The other tables are added implecitly
Pobiega
Pobiega2y ago
So fix that.
Angius
Angius2y ago
^
Pobiega
Pobiega2y ago
If you want direct access, add direct access.
Angius
Angius2y ago
Then you just do
return await _dbContext.Containers
.Where(c => c.Department.Site.Company.Enterprise.Id == id)
.ToListAsync();
return await _dbContext.Containers
.Where(c => c.Department.Site.Company.Enterprise.Id == id)
.ToListAsync();
Pobiega
Pobiega2y ago
That would give you all containers that match a given enterprise Id
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?