我有以下类(class):
public class Employee
{
public string Name {get; set;}
...
}
和 EF Core 2.1 中的 LINQ 查询
Employee GetEmployeeByName(string name) {
return Context.Employee.Where ( w =>String.Compare(w.Name, name, true) == 0).FirstOrDefault();
}
转换为Net Core EF 3.1后,出现错误。
LINQ expression 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()
, orToListAsync()
我必须将查询更改为
Employee GetEmployeeByName(string name) {
return Context.Employee.Where ( w =>w.Name.ToLower() == name.ToLower()).FirstOrDefault();
}
有一个更好的方法吗?
最佳答案
如果您在进行不区分大小写的字符串比较,建议 (AFAIK) 是使用 EF.Functions扩展,转换成正确的 SQL 语句。
你的例子变成了这个(使用 Like ):
using Microsoft.EntityFrameworkCore;
Employee GetEmployeeByName(string name) {
return Context.Employee.Where(w => EF.Functions.Like(w.Name, name)).FirstOrDefault();
}
这转化为类似的东西(取决于服务器版本)
SELECT TOP(1) <<list of fields here>> FROM Employee WHERE Name LIKE(@name)
functions which are available取决于 EF Core 和底层 DBMS 的版本,但由于您提到了 SQL Server,假设您使用了“默认”排序规则,上述内容将起作用。相关:Is the LIKE operator case-sensitive with MSSQL Server?
关于c# - Net core EF 3.1 LINQ 字符串比较不再有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59795841/