C
C#10mo ago
Ole

❔ 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
Pobiega10mo ago
If you only want the container, why start from enterprises? Go directly for container.
Ole
Ole10mo ago
The dbContext only has the enterprise attribute. The other tables are added implecitly
Pobiega
Pobiega10mo ago
So fix that.
Angius
Angius10mo ago
^
Pobiega
Pobiega10mo ago
If you want direct access, add direct access.
Angius
Angius10mo 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
Pobiega10mo ago
That would give you all containers that match a given enterprise Id
Accord
Accord10mo 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.