开发者

Entity framework null value in query

开发者 https://www.devze.com 2023-03-30 03:59 出处:网络
I\'m seeing a strange behavior in an EF query adn I\'m wondering why 开发者_运维知识库it is happening.

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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消