Linq 查询适用于 null 但不适用于 int? 在 where 子句中
我有一个像(简化的)这样的 linq 查询函数:
public IList<Document> ListDocuments(int? parentID)
{
return (
from doc in dbContext.Documents
where doc.ParentID == parentID
select new Document
{
ID = doc.ID,
ParentID = doc.ParentID,
Name = doc.SomeOtherVar
}).ToList();
}
现在,由于某种原因,当我为parentID 传入null 时(当前只有具有nullparentID 的数据),但我没有得到任何结果。
我将此查询复制并粘贴到 LinqPad 中并运行以下命令:
from doc in dbContext.Documents
where doc.ParentID == null
select doc
我按预期返回结果集...
实际查询已留下联接和其他联接,但我已删除它们并对其进行测试并获得相同的结果,因此联接是不影响任何事情。 该应用程序和 LinqPad 也都连接到同一个数据库。
编辑:在应用程序查询中仅使用“null”进行测试,它按预期返回结果,因此问题是使用 null 与 int?。 我更新了问题,以使其他有相同问题的人更有用地找到此线程。
I have a linq query function like (simplified):
public IList<Document> ListDocuments(int? parentID)
{
return (
from doc in dbContext.Documents
where doc.ParentID == parentID
select new Document
{
ID = doc.ID,
ParentID = doc.ParentID,
Name = doc.SomeOtherVar
}).ToList();
}
Now for some reason when I pass in null for the parentID (currently only have data with null parentIDs) and I get no results.
I copy and paste this query into LinqPad and run the following:
from doc in dbContext.Documents
where doc.ParentID == null
select doc
I get back a result set as expected...
The actually query has left join's and other joins but I have removed them and tested it and get the same result so the joins are not affecting anything. The app and LinqPad are both connected to the same DB as well.
Edit: Tested with just 'null' in the appliction query and it returns the result as expected so the issue is using null vs int?. I have updated question to make it more useful to others with the same issue to find this thread.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
文字
null
值的处理方式与可能为 null 的参数不同。 当您显式测试null
时,生成的 SQL 将使用IS NULL
运算符,但当您使用参数时,它将使用标准= 运算符,这意味着没有行会匹配,因为在 SQL 中
null
不等于任何内容。 这是 LINQ to SQL 中最烦人的 .NET/SQL 语义不匹配之一。 要解决这个问题,您可以使用如下子句:Literal
null
values are handled differently than parameters which could be null. When you explicitly test againstnull
, the generated SQL will use theIS NULL
operator, but when you're using a parameter it will use the standard=
operator, meaning that no row will match because in SQLnull
isn't equal to anything. This is one of the more annoying .NET/SQL semantic mismatches in LINQ to SQL. To work around it, you can use a clause like:您也可以使用类似的东西...
它对我有用!
希望它对你有用!
You can use also something like ...
It worked for me!
hope it work for you!