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

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

问题描述

Visual Studio 中的 LINQ-to-SQL 查询生成一个有错误的 SQL 查询.在 LINQPad 中,使用相同数据库(或 DataContext)的相同 LINQ 查询运行得很好.

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.

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;

这是生成的 SQL 的一小部分发生错误的地方:

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

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

在 where 子句中的等号之后,实际上什么都没有!在 LINQPad 的 SQL 查询中我们看到了很好的 where 子句:

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 (...)

当我逐行比较从 VS 和 LINQPad 生成的两个 SQL 查询时,这是同一件事.除了 LINQPad 使用 params 以及 Visual Studio 的 where 子句中缺少 equal 的右侧部分,如前所示.

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.

在 LINQ 查询中,我在 where 子句中尝试使用以下语法:

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

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

但也会产生不好的结果.我什至在 LINQ 查询之前尝试过这样的事情:

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

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

注意事项 2

属性是可为空的整数.如果属性为空,我确实希望在查询中为空.显然,如果有价值,我想要财产的价值.

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.

我已经尝试过在这个问题中提出的命题:Linq where column ==(空引用)与 column == null 不同

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

...没有成功.

对两个相似的 LINQ 查询的任何解释,但生成一个好的和一个坏的 SQL 查询?有什么建议可以解决这个问题吗?

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

谢谢!

推荐答案

试试这个:

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

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

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