Linq查询使用null但不是int? 在where子句中

我有一个linq查询函数,如(简化):

public IList ListDocuments(int? parentID) { return ( from doc in dbContext.Documents where doc.ParentID == parentID select new Document { ID = doc.ID, ParentID = doc.ParentID, Name = doc.SomeOtherVar }).ToList(); } 

现在由于某种原因,当我为parentID传递null(当前只有具有null parentID的数据)时,我没有得到任何结果。

我将此查询复制并粘贴到LinqPad中并运行以下命令:

 from doc in dbContext.Documents where doc.ParentID == null select doc 

我按预期收回结果集…

实际的查询已经离开了连接和其他连接,但我已经删除它们并测试它并得到相同的结果,因此连接不会影响任何东西。 该应用程序和LinqPad也连接到同一个数据库。

编辑:在应用程序查询中仅使用“null”进行测试,并按预期返回结果,因此问题是使用null vs int?。 我已经更新了问题,使其对具有相同问题的其他人更有用,可以找到这个post。

Literal null值的处理方式与可能为null的参数的处理方式不同。 当您显式测试null ,生成的SQL将使用IS NULL运算符,但是当您使用参数时,它将使用standard =运算符,这意味着没有行匹配,因为在SQL中null不等于任何内容。 这是LINQ to SQL中令人烦恼的.NET / SQL语义不匹配之一。 要解决它,您可以使用如下的子句:

 where doc.ParentID == parentID || (doc.ParentID == null && parentID == null) 

你也可以用…

 from doc in dbContext.Documents where doc.IsParentIDNull() select doc 

它对我有用! 希望它对你有用!