实体框架查询中的空值

发布于 2024-11-30 10:48:01 字数 411 浏览 2 评论 0原文

我在 EF 查询中看到奇怪的行为,我想知道为什么会发生这种情况。 使用以下代码,我没有得到任何结果:

if (category.Parent == null)
{
    return Db.EventCategories.Where(c => c.Parent == category.Parent);
}

但使用此代码,它确实返回了预期结果:

if (category.Parent == null)
{
    return Db.EventCategories.Where(c => c.Parent == null);
}

有什么区别? null不是总是null吗?或者当值为空时(Parent 的类型为 int?),EF 是否将它们视为不同的元素。

I'm seeing a strange behavior in an EF query adn I'm wondering why it is happening.
With the following code I don't get any results:

if (category.Parent == null)
{
    return Db.EventCategories.Where(c => c.Parent == category.Parent);
}

But with this code it does return the expected results:

if (category.Parent == null)
{
    return Db.EventCategories.Where(c => c.Parent == null);
}

What is the difference? Isn't null always null? or does the EF treats them as different elements when the value is a nullable (Parent is of type int?).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

熊抱啵儿 2024-12-07 10:48:01

我不是 100% 确定,但我认为第一个语句会生成类似 SELECT ...
FROMcategory,eventcategoriesWHEREcategory.parent=eventcategories.parent
(如果category.parent为空,则返回空记录集),而第二个...WHEREeventcategories.parentISNULL

I'm not 100% sure, but I think the first statement generates something like SELECT ...
FROM category, eventcategories WHERE category.parent = eventcategories.parent
(which returns empty recordset if category.parent is null), whereas the second ... WHERE eventcategories.parent IS NULL.

独自唱情﹋歌 2024-12-07 10:48:01

请参阅本文中的详细说明:NULL 值处理在实体框架中。请注意,EF 5.0、6.0 和 6.1 对可为空值的处理方式不同。在 EF 5.0 中,您将需要手动测试 null;默认情况下,两个变量之间的方程比较不会测试空值。您还可以在DbContext.ContextOptions中手动打开UseCSharpNullComparisonBehavior属性来达到相同的效果。在 EF 6.0 中,默认情况下会启用 null 比较,但可能过于激进,甚至在不可为 null 的列上启用 null 比较,从而导致性能降低。 EF 6.1 应该调整了算法,只在需要时测试空值。

Please see a detailed explanation in this article: NULL Value Handling in Entity Framework. Beware that EF 5.0, 6.0 and 6.1 handle the nullable values differently. In EF 5.0, you will need to manually test for nulls; an equation comparison between two variables does not test for nulls by default. You can also turn on the UseCSharpNullComparisonBehavior property manually in the DbContext.ContextOptions to achieve the same effect. In EF 6.0, null comparison is turned on by default, but probably over-aggressively and even on non-nullable columns, resulting in slower performance. EF 6.1 is supposed to have tweaked the algorithm to only test nulls when needed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文