c# - Net core EF 3.1 LINQ 字符串比较不再有效

标签 c# linq entity-framework-core ef-core-3.1

我有以下类(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(), or ToListAsync()



我必须将查询更改为
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/

相关文章:

c# - Entity Framework Core - 包括集合的多个属性级别

c# - WinSCP .NET 程序集拒绝 RSA/DSA key 指纹

c# - 使用 LINQ 的结构与类

c# - 更改 LINQ 对象数据上下文

c# - LINQ 查询中的自定义比较器对字符串/数字进行排序

c# - Entity Framework Core 通过 SSH 隧道连接到 MSSQL 数据库

c# - EF : The instance of entity type X cannot be tracked because another instance of this type with the same key is already being tracked

c# - UDP - 我可以发送两个数据报部分,并让接收端将它们合并为一个吗?

c# - 在托管代码中,如何实现良好的引用位置?

c# - 有人帮我解释一下这个 for 循环的一部分吗