使用 LINQ-to-SQL 处理 where 子句中的空值
- 作者: 我不是律师
- 来源: 51数据库
- 2022-12-13
问题描述
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)
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
