简体   繁体   English

LINQ 表达式过滤

[英]LINQ expression to filter

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.我有以下LINQ表达式,我正在获取Courses ,属于该CourseStudents ,然后是Student去的School The following LINQ expression works fine.以下 LINQ 表达式工作正常。

However, I need to further, filter it where I need to get Students with the City == 'Colarado' .但是,我需要进一步过滤它,在我需要让Students with the City == 'Colarado'地方进行过滤。 How can I alter the following LINQ to my use case.如何将以下 LINQ 更改为我的用例。

     _dbContext.Courses
         .Where(c => c.Id == Id)
         .Include(c => c.Students)
             .ThenInclude(c => c.Schools)
         .OrderByDescending(c => c.Id)
         .ToListAsync();

If you need all courses and only filter students - since EF Core 5.0 you can use filtered include :如果您需要所有课程并且只过滤学生 - 从 EF Core 5.0 开始,您可以使用过滤的包括

 _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(); 

You can do the filter in the Where method.您可以在Where方法中进行筛选。

_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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM