LINQ的其中column = =(空引用)不一样,列== NULLLINQ、column、NULL

2023-09-02 10:30:43 作者:在你心里睡一下

我碰到一个很奇怪的问题,LINQ到SQL。在下面的例子中,

I came across a rather strange problem with linq-to-sql. In the following example,

var survey = (from s in dbContext.crmc_Surveys
                                   where (s.crmc_Retail_Trade_Id == tradeId) && (s.State_.Equals(state))
                                   select s).First();

如果tradeId为null,它不表现为,如果我指定的专门空而不是像这样,

If tradeId is null, it doesn't behave as if I had specified null specifically like this instead,

var survey = (from s in dbContext.crmc_Surveys
                                   where (s.crmc_Retail_Trade_Id == null) && (s.State_.Equals(state))
                                   select s).First();

这是我所期望的行为。事实上,除非两个值都非空,它不返回任何东西。我无法弄清楚如何做到这短短的几个不同的LINQ查询。任何想法?

Which is my desired behavior. In fact it doesn't return anything unless both values are non-null. I can't figure out how to accomplish this short of several different linq queries. Any ideas?

推荐答案

修改其中(s.crmc_Retail_Trade_Id == tradeId)

where (s.crmc_Retail_Trade_Id == tradeId || 
      (tradeId == null && s.crmc_Retail_Trade_Id == null))

编辑 - 基于这个职位由的布兰特Lamborn,它看起来像下面会做你想要的:

Edit - based on this post by Brant Lamborn, it looks like the following would do what you want:

where (object.Equals(s.crmc_Retail_Trade_Id, tradeId))

借助 null语义(LINQ到SQL) MSDN页面链接到一些有趣的信息:

The Null Semantics (LINQ to SQL) MSDN page links to some interesting info:

LINQ to SQL的不征收C#null或   Visual Basic中没有对比   语义上的SQL。比较运算符   在语法翻译成自己的   SQL当量。语义反映   由服务器定义的SQL语法或   连接设置。两个空值   被认为是在默认的不平等   SQL Server的设置(尽管你可以   改变设置来改变   语义)。无论如何,LINQ to SQL的   不考虑服务器设置   查询翻译。

LINQ to SQL does not impose C# null or Visual Basic nothing comparison semantics on SQL. Comparison operators are syntactically translated to their SQL equivalents. The semantics reflect SQL semantics as defined by server or connection settings. Two null values are considered unequal under default SQL Server settings (although you can change the settings to change the semantics). Regardless, LINQ to SQL does not consider server settings in query translation.

字面空的比较   (没有)被翻译成   相应的SQL版本(is null或is   NOT NULL)。

A comparison with the literal null (nothing) is translated to the appropriate SQL version (is null or is not null).

的空(没有)中的价值   排序规则是由SQL Server的定义;   LINQ to SQL不改变   整理。

The value of null (nothing) in collation is defined by SQL Server; LINQ to SQL does not change the collation.