Reputation: 16841
I have the following LINQ
expression where I am fetching Courses
, Students
that belong to that Course
, then the School
's where the Student
's goes to. The following LINQ expression works fine.
However, I need to further, filter it where I need to get Students
with the City == 'Colarado'
. How can I alter the following LINQ to my use case.
_dbContext.Courses
.Where(c => c.Id == Id)
.Include(c => c.Students)
.ThenInclude(c => c.Schools)
.OrderByDescending(c => c.Id)
.ToListAsync();
Upvotes: 0
Views: 100
Reputation: 141635
If you need all courses and only filter students - since EF Core 5.0 you can use filtered include:
_dbContext.Courses
.Where(c => c.Id == Id)
.Include(c => c.Students.Where(s => s.City == "Colarado"))
.ThenInclude(c => c.Schools)
.OrderByDescending(c => c.Id)
.ToListAsync();
Upvotes: 4
Reputation: 9626
You can do the filter in the Where
method.
_dbContext.Courses
.Where(c => c.Id == Id && c.Students.All(s => s.City == "Colarado"))
.Include(c => c.Students)
.ThenInclude(c => c.Schools)
.OrderByDescending(c => c.Id)
.ToListAsync();
Upvotes: 1