【问题标题】:EF 6.1.3, Linq query with the filter where columnname == NULL is not fetching any rowsEF 6.1.3,使用 columnname == NULL 的过滤器的 Linq 查询未获取任何行
【发布时间】:2016-06-09 10:49:49
【问题描述】:

技术:EF 6.1.3、数据库优先方法和 SQL Server。

问题:我遇到了以下 Linq 查询的问题,

EmployeeEntities db = new EmployeeEntities();
IQueryable<Model.Employee> employees = from e in db.Employee
                                       where e.EmployeeName == null
                                       select e;

我正在尝试获取 EmployeeName 为 Null 的员工,但我没有得到任何记录,而当我在数据库 (SQL Server) 中查询时,我得到了正确的结果。

我怀疑 linq 查询没有将 where 子句转换为 EmployeeName IS NULL,但它只是转换为 EmployeeName == null

请告诉我如何解决这个问题..

谢谢, 普拉卡什。

【问题讨论】:

  • 能否贴出生成的SQL,例如var sql = employees.ToString();
  • 也许 EmployeeName 不是 null 而是空字符串。如果您将|| e.EmployeeName.Equals("") 添加到您的where 子句中,您能检查一下会发生什么吗?
  • 在 EF 6 中,您可以使用 where string.IsNullOrEmpty(e.EmployeeName)
  • @LiviuM。好的,很酷,我不知道。我记得它在 Linq 查询中被破坏了,但不确定 EF 版本。
  • WHERE ([Extent1].[EmployeeName] = @p__linq__0) 由于办公原因,我没有粘贴完整代码..

标签: entity-framework entity-framework-6 entity-framework-5


【解决方案1】:

您需要调用ToList() 来实现查询。 EF 肯定会转换为 SQL 中正确的运算符。

所以代码变成了:

List<Model.Employee> employees = (from e in db.Employee
                                       where e.EmployeeName == null
                                       select e).ToList();

【讨论】:

  • 是的..我正在使用 ToList() 来获取结果,但它没有返回任何在 EmployeeName 列中有 null 的行..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-17
  • 1970-01-01
  • 2015-10-18
  • 1970-01-01
  • 1970-01-01
  • 2013-04-29
  • 1970-01-01
相关资源
最近更新 更多