5

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

3
  • Do you modify the category object before you actually run the query? Commented Aug 21, 2011 at 17:41
  • No, I don't. I think @a1ex01 is right, if you don't use the constant null it won't generate the IS NULL query Commented Aug 21, 2011 at 18:38
  • Have you checked the generated SQL? Commented Aug 21, 2011 at 18:44

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.