Why these two methods work differently:
public List<Foo> GetFoos()
{
int? parentId = null;
var l = _dataContext.Foos.Where(x => x.ParentElementId == parentId).ToList();
return l;
}
public List<Foo> GetFoos()
{
var l = _dataContext.Foos.Where(x => x.ParentElementId == null).ToList();
return l;
}
The first one returns nothing. Second returns what was expected. Data comes from EF. ParentElementId is nullable.
That is because you can’t compare to null in SQL, it has the special
IS NULLoperator to check for null values.The first query will be translated into a comparison, where the parameter is null:
This doesn’t work, because comparing two null values doesn’t yield true.
The second query will be translated into a null check, because the null value is a constant:
This works because EF is not fooled to translate it into a comparison.