5

The following works as expected (LINQ to Entities):

var topics = (from t in ctx.Topics where t.SubjectId == subjectId && t.ParentId == null select new { t.Title, t.Id }).ToList();

However, the following returns nothing:

int? parent = null;
var topics = (from t in ctx.Topics where t.SubjectId == subjectId && t.ParentId == parent select new { t.Title, t.Id }).ToList();

Topic.ParentId is a nullable int. It's easy to work around, but this puzzles me. Can anyone shed any light?

James
  • 7,343
  • 9
  • 46
  • 82
  • Same question here: http://stackoverflow.com/questions/682429/how-can-i-query-for-null-values-in-entity-framework/4262617#4262617 – Slauma Apr 12 '11 at 18:58

1 Answers1

4

You are definately not the first person to observe this... interesting... behavior.

http://connect.microsoft.com/data/feedback/details/607404/entity-framework-and-linq-to-sql-incorrectly-handling-nullable-variables

In short, it's difficult to handle different ways of expressing null.

Thebigcheeze
  • 3,408
  • 2
  • 22
  • 18
  • 1
    Thank you. From the link in your answer, I found an easy workaround: t.ParentId.Equals(parent). But how strange! I'm glad it's not just me going crazy! – James Apr 12 '11 at 18:59
  • @James, I though this work around only works for Linq to SQL and not Linq to Entities... Did it work for Linq to Entities for you? – Andrew Savinykh Apr 13 '11 at 04:44
  • @zespri No, I posted too soon! It works when parent is null, but not in other cases. I ended up with if (parent==null) ... – James Apr 13 '11 at 16:49