简体   繁体   English

当where子句与NULL值进行比较时,LINQ-to-SQL查询不返回行

[英]LINQ-to-SQL query not returning row when where clause compares against NULL value

Lets consider a table with 2 columns: ID (int) and Role(string). 让我们考虑一个包含2列的表:ID(int)和Role(字符串)。 Both are nullable. 两者都可以为空。

Now assume that the data in the two columns is: 现在假设两列中的数据是:

ID     Role
--     ----
 1     NULL
 2     Admin

The query looks like this: 查询如下所示:

List<types> t1 = (
    from a in datacontext.RoleTable 
    where a.Role != "Admin"
    select a
).ToList();

I thought the above query should be returning the first record of the table as its Role column is not equal to 'Admin' but the query returns an empty list. 我认为上面的查询应该返回表的第一条记录,因为它的Role列不等于'Admin',但查询返回一个空列表。

Now when I use this query: 现在,当我使用此查询时:

List<types> t2 = (
    from a in datacontext.RoleType 
    where a.Role != "Admin" && a.Role == DBNull.Value.ToString() 
    select a
).ToList();

I get the correct answer. 我得到了正确的答案。

Can anybody tell me why the first query is not working please. 任何人都可以告诉我为什么第一个查询不起作用。

FYI: If the Role column in the first row in the table is changed to User instead of NULL then the first query works fine. 仅供参考:如果表中第一行中的Role列更改为User而不是NULL则第一个查询可以正常工作。

I am using SQL Express and LINQ to SQL. 我正在使用SQL Express和LINQ to SQL。

The first query doesn't behave as expected, because it is translated into SQL that is equivalent to the following: 第一个查询的行为不符合预期,因为它被转换为SQL,它等效于以下内容:

select * from RoleTable where Role != 'Admin'

Now, in SQL NULL != 'Admin' is not TRUE (nor is it FALSE - it is undefined). 现在,在SQL NULL != 'Admin' 不是 TRUE (也不是FALSE - 它是未定义的)。
That's one of the many cases where the abstraction that LINQ to SQL provides is leaky and you still need to know SQL. 这是LINQ to SQL提供的抽象漏洞并且您仍然需要知道SQL的许多情况之一。

BTW: Your second query is also incorrect, it will select only those rows that are null . 顺便说一句:你的第二个查询也是错误的,它只会选择那些为null行。 It wouldn't select a row with the role 'User' . 它不会选择具有'User'角色的行。

The correct query would look like this: 正确的查询将如下所示:

List<types> t2 = 
    (from a in datacontext.RoleTable 
     where a.Role != "Admin" || a.Role == null 
     select a).ToList();

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

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