【发布时间】:2021-11-10 10:27:18
【问题描述】:
这是我在 where 子句中传递的自定义过滤器(Func)
Func<Project,bool> filter = f =>
{
bool filteredContent = true;
if (!CreatorId.Equals(0))
filteredContent = f.CreatedBy.Equals(CreatorId);
if (filteredContent && !VerticalMarketId.Equals(0))
filteredContent = f.VerticalMarketsId.Equals(VerticalMarketId);
if (filteredContent && !ProductCategoryId.Equals(0))
filteredContent = f.ProductCategoriesId.Equals(ProductCategoryId);
return filteredContent;
};
这是我的代码,我根据过滤器表达式中创建的条件获取所有项目
getProjects = await _context.Projects.Where(x => x.IsDeleted == false && filter.Invoke(x))// Here I'm getting the exception
.Include(PC => PC.ProjectComments.Where(x => x.IsDeleted == false))
.Include(SP => SP.SharedProjects)
.AsNoTracking().ToListAsync();
异常:无法使用 LINQ 表达式 (DbSet......) 翻译。要么以可以翻译的形式重写查询, 或通过插入调用显式切换到客户端评估 “AsEnumerable”、“AsAsyncEnumerable”、“ToList”或“ToListAsync”。
谁能告诉我如何使用表达式过滤数据?
注意:我可以在应用过滤器之前执行 ToListAsync(),但它会从数据库中获取所有记录,然后在客户端过滤。但我想过滤服务器端的数据。
【问题讨论】:
-
您需要
Expression<Func<Project, bool>>,EF 才能翻译它 -
您能详细说明一下吗? @HansKesting
标签: c# linq entity-framework-core where-clause iqueryable