可以为 null 的 Linq 表达式
看起来是个愚蠢的问题,但我就是不明白。 我的实体:
public class Page
{
public int Id { get; set; }
//...
public int? ParentId { get; set; }
}
在控制器中:
db.Pages.First(x => x.ParentId == null);
按预期工作(返回一些元素)。 但是:
int? test = null;
db.Pages.First(x => x.ParentId == test);
抛出 Sequence contains no elements
我错过了什么?
Looks like stupid question, but I just dont get it.
My entity:
public class Page
{
public int Id { get; set; }
//...
public int? ParentId { get; set; }
}
In controller:
db.Pages.First(x => x.ParentId == null);
Works as expected (returns some element).
But:
int? test = null;
db.Pages.First(x => x.ParentId == test);
Throws Sequence contains no elements
What do I miss?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我相信某些 LINQ 提供程序的空值存在奇怪之处。尝试:
或者,针对不同的情况使用不同的查询:
基本上这是因为 SQL 将 NULL 视为不等于其自身,因此:
如果 X 和 Y 均为空值,仍然会失败。使用
== null
部分(带有文字 null)强制转换为ISNULL
或任何 SQL 等效项。我同意这很痛苦,其他人可能有更好的解决方法,但这可能会帮助您继续前进。
I believe there's an oddity around nulls with some LINQ providers. Try:
Alternatively, use different queries for the different situations:
Basically this is because SQL treats NULL as unequal to itself, so:
will still fail if both X and Y are null values. Using the
== null
part (with a literal null) forces a conversion toISNULL
or whatever the SQL equivalent is.I agree it's a pain, and someone else may have a better workaround, but this may help you get going.
您可以执行类似的操作作为解决方法:
我假设由于
int?
实际上是一个Nullable
我们的 linq-to-entities 提供程序不会比较事物正确的。You could do something like this as a workaround:
I'm assuming since
int?
is actually aNullable<int>
our linq-to-entities provider isn't comparing things right.试试这个(根据 gdoron 的评论进行修改。现在正是 gideon 发布的内容,所以请接受他的而不是我的):
Try this (modified according to gdoron's comment. It now is exactly what gideon posted, so please accept his instead of mine):