操作使用LINQ到SQL where子句中的空值 [英] Handling null values in where clause using LINQ-to-SQL

查看:159
本文介绍了操作使用LINQ到SQL where子句中的空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在LINQ到SQL查询在Visual Studio生成有错误的SQL查询。在LINQPad,使用同一数据库中的相同LINQ查询(或DataContext的)运行就好了。



LINQ查询



<$在db.Access
$ p p> VAR accesDomaines =从t其中t.IdUser == access.IdUtilisateur
,其中t.IdDomain!= NULL
,其中吨。 IdRole == access.IdRole
,其中t.IdPlace == access.IdPlace
选择吨;

下面是生成的SQL的一小部分,其中发生错误:

  WHERE(...)AND([T3]。[IdRole] =)和(...)

在where子句中,有几乎一无所有等号后!在LINQPad的SQL查询,我们看到了良好的where子句:

  WHERE(...)AND([T3] [ IdRole] IS NULL)AND(...)

当我比较来自VS两个生成的SQL查询和LINQPad,一行行,这是同样的事情。除了LINQPad使用PARAMS也是在Visual Studio中的条款,如前所示的平等缺少右侧部分。






注1



在LINQ查询,我试着用这个语法在子句:

 其中t.IdRole.Equals(acces.IdRole.Value)

但也产生一个坏的结果。我甚至尝试这样的事情LINQ查询之前:

 如果(!acces.IdRole.HasValue){acces.IdRole = NULL ; } 



注2



属性是可空整数。我想查询为空,如果属性为null。很显然,我要的属性的值,如果有一个值。



注3



我曾尝试命题在这个问题上取得:的LINQ where列== (空引用)不一样的列== NULL



...,但没有成功。






任何解释两个类似的LINQ查询,但产生好的和坏的SQL查询?任何建议来解决这个问题?



感谢您!


解决方案

试试这个:

 其中的Object.Equals(t.IdRole,access.IdRole)


The LINQ-to-SQL query in Visual Studio generates an SQL query with errors. In LINQPad, the same LINQ query using the same database (or DataContext) runs just fine.

LINQ Query

var accesDomaines = from t in db.Access
                  where t.IdUser == access.IdUtilisateur
                  where t.IdDomain != null
                  where t.IdRole == access.IdRole
                  where t.IdPlace == access.IdPlace
                  select t;

Here's a small part of generated SQL where the error occurs:

WHERE (...) AND ([t3].[IdRole] = ) AND (...)

After the equals in where clause, there's literally nothing ! In the SQL query of LINQPad we see the good where clause:

WHERE (...) AND ([t3].[IdRole] IS NULL) AND (...)

When I compare the two generated SQL queries from VS and LINQPad, line by line, this is the same thing. Except LINQPad is using params and also the missing right part of equal in where clause of Visual Studio, as shown before.


Note 1

In the LINQ query, I tried with this syntax in where clauses:

where t.IdRole.Equals(acces.IdRole.Value)

But also generates a bad result. I even tried something like this before the LINQ query:

if (!acces.IdRole.HasValue) { acces.IdRole = null; }

Note 2

Properties are nullable integers. I do want null in query if property is null. Obviously, I want the value of property if there's a value.

Note 3

I have tried the proposition made in this question: Linq where column == (null reference) not the same as column == null

...with no success.


Any explanation of two similar LINQ queries, but generating a good and a bad SQL query? Any suggestion to solve this problem?

Thank you!

解决方案

try this:

where object.Equals(t.IdRole, access.IdRole)

这篇关于操作使用LINQ到SQL where子句中的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆