简体   繁体   English

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

[英]Linq query works with null but not int? in where clause

I have a linq query function like (simplified): 我有一个linq查询函数,如(简化):

public IList<Document> 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();
}

Now for some reason when I pass in null for the parentID (currently only have data with null parentIDs) and I get no results. 现在由于某种原因,当我为parentID传递null(当前只有具有null parentID的数据)时,我没有得到任何结果。

I copy and paste this query into LinqPad and run the following: 我将此查询复制并粘贴到LinqPad中并运行以下命令:

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

I get back a result set as expected... 我按预期得到了一个结果集......

The actually query has left join's and other joins but I have removed them and tested it and get the same result so the joins are not affecting anything. 实际的查询已经离开了连接和其他连接,但我已经删除它们并测试它并得到相同的结果,因此连接不会影响任何东西。 The app and LinqPad are both connected to the same DB as well. 该应用程序和LinqPad也连接到同一个数据库。

Edit: Tested with just 'null' in the appliction query and it returns the result as expected so the issue is using null vs int?. 编辑:在应用程序查询中仅使用'null'进行测试,并按预期返回结果,因此问题是使用null vs int?。 I have updated question to make it more useful to others with the same issue to find this thread. 我已经更新了问题,使其对具有相同问题的其他人更有用,可以找到这个帖子。

Literal null values are handled differently than parameters which could be null. Literal null值的处理方式与可能为null的参数的处理方式不同。 When you explicitly test against null , the generated SQL will use the IS NULL operator, but when you're using a parameter it will use the standard = operator, meaning that no row will match because in SQL null isn't equal to anything. 当您显式测试null ,生成的SQL将使用IS NULL运算符,但是当您使用参数时,它将使用standard =运算符,这意味着没有行匹配,因为在SQL中null不等于任何内容。 This is one of the more annoying .NET/SQL semantic mismatches in LINQ to SQL. 这是LINQ to SQL中令人烦恼的.NET / SQL语义不匹配之一。 To work around it, you can use a clause like: 要解决它,您可以使用如下的子句:

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

You can use also something like ... 你也可以用...

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

It worked for me! 它对我有用! hope it work for you! 希望它对你有用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM