如何在.NET EF核心中为where子句传递多个筛选器



如下所示,我将向存储库类传递一个lambda表达式,以根据用户的id筛选用户。

_repository.GetStudentUsers(studentUser => studentUser.StudentId.Equals(srequest.Id));

这就是存储库类中的GetAStudentUsers方法的样子。

public IQueryable<StudentUser> GetAStudentUsers(Expression<Func<StudentUser, bool>>? filter = null)
{
if (filter is not null)
{
return dbContext.StudentUsers
.AsQueryable()
.AsNoTracking()
.Where(filter)
.OrderBy(t => t.StudentName);
}
else
{
return dbContext.StudentUsers
.AsQueryable()
.AsNoTracking()
.OrderBy(t => t.StudentName);
}
}

我的问题是如何修改它以将多个筛选器传递给存储库类中的方法。当我添加它显示的多个lambda表达式时,不能对bool类型的操作数使用&&运算符。

您可以多次调用Where方法。它构建查询,有效地AND过滤。在实际枚举IQueryable端点之前,它不会构建实际的SQL并查询数据库。

像这样:

public IQueryable<StudentUser> GetAStudentUsers(params Expression<Func<StudentUser, bool>>[] filters)
{
// prepare a base query
var query = dbContext.StudentUsers
.AsQueryable()
.AsNoTracking();
// apply filters
if (filters != null)
{
foreach (var filter in filters) query = query.Where(filter);
}
// finalize the query by ordering the results
return query.OrderBy(t => t.StudentName);
}

最新更新