EF创建的数据库查询出现问题



我想从数据库下载过滤后的数据。

在这里它过滤数据

return predicate
.And(true, () => company => !String.IsNullOrEmpty(searchCriteria.Keyword) ? searchCriteria.Keyword.Contains(company.Name) : true)
.Or(true, () => company => !String.IsNullOrEmpty(searchCriteria.Keyword) ? company.Employees.Any(x => x.FirstName == searchCriteria.Keyword) : true)
.Or(true, () => company => !String.IsNullOrEmpty(searchCriteria.Keyword) ? company.Employees.Any(x => x.LastName == searchCriteria.Keyword) : true)
.And(true, () => company => searchCriteria.EmployeeDateOfBirthFrom != null ? company.Employees.Any(x => x.DateOfBirth >= searchCriteria.EmployeeDateOfBirthFrom) : true)
.And(true, () => company => searchCriteria.EmployeeDateOfBirthTo != null ? company.Employees.Any(x => x.DateOfBirth <= searchCriteria.EmployeeDateOfBirthTo) : true)
.And(true, () => company => searchCriteria.EmployeeJobTitles != null ? company.Employees.Any(x=> searchCriteria.EmployeeJobTitles.Any(s=> s == x.JobTitle.ToString())) : true);

我在这里从数据库下载数据:

return await dbContext.Companies.Include(x => x.Employees).Where(predicate).ToListAsync();

为什么我有这个问题,我能解决吗?

System.InvalidOperationException: The LINQ expression 'DbSet<Employee>
.Where(e => EF.Property<Nullable<long>>((EntityShaperExpression: 
EntityType: Company
ValueBufferExpression: 
(ProjectionBindingExpression: EmptyProjectionMember)
IsNullable: False
), "Id") != null && EF.Property<Nullable<long>>((EntityShaperExpression: 
EntityType: Company
ValueBufferExpression: 
(ProjectionBindingExpression: EmptyProjectionMember)
IsNullable: False
), "Id") == EF.Property<Nullable<long>>(e, "CompanyId"))
.Any(e => __searchCriteria_EmployeeJobTitles_0
.Contains(e.ToString()))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.<VisitMethodCall>g__CheckTranslated|8_0(ShapedQueryExpression translated, <>c__DisplayClass8_0& )

EF Core无法翻译以下表达式:

company.Employees.Any(x => searchCriteria.EmployeeJobTitles
.Any(s => s == x.JobTitle.ToString()))

它有两个问题。

首先,searchCriteria.EmployeeJobTitles似乎在内存集合中,而内存集合中当前唯一可翻译的运算符是Contains

所以应该改为

company.Employees.Any(x => searchCriteria.EmployeeJobTitles
.Contains(x.JobTitle.ToString()))

但根据异常消息,你已经这么做了。这就引出了第二个问题:x.JobTitle属性类型似乎是enum,而enum的ToString()无法转换。

因此,您必须以其他方式执行枚举过滤器-将searchCriteria.EmployeeJobTitlesIEnumerable<string>转换为IEnumerable<JobTitle>并使用Contains(x.JobTitle),这样可以避免x.JobTitle.ToString():

company.Employees.Any(x => searchCriteria.EmployeeJobTitles
.Select(t => Enum.Parse<JobTitle>(t))
.Contains(x.JobTitle))
构建谓词时,请将x.JobTitle.ToString()更改为x.JobTitle。数据库端不支持ToString()

最新更新