❔ 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
Pobiega15mo ago
If you only want the container, why start from enterprises? Go directly for container.
Ole (ping please)
Ole (ping please)OP15mo ago
The dbContext only has the enterprise attribute. The other tables are added implecitly
Pobiega
Pobiega15mo ago
So fix that.
Angius
Angius15mo ago
^
Pobiega
Pobiega15mo ago
If you want direct access, add direct access.
Angius
Angius15mo 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
Pobiega15mo ago
That would give you all containers that match a given enterprise Id
Accord
Accord15mo 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.
Want results from more Discord servers?
Add your server