Looks like stupid question, but I just dont get it.
My entity:
public class Page
{
public int Id { get; set; }
//...
public int? ParentId { get; set; }
}
In controller:
db.Pages.First(x => x.ParentId == null);
Works as expected (returns some element).
But:
int? test = null;
db.Pages.First(x => x.ParentId == test);
Throws Sequence contains no elements
What do I miss?
I believe there’s an oddity around nulls with some LINQ providers. Try:
Alternatively, use different queries for the different situations:
Basically this is because SQL treats NULL as unequal to itself, so:
will still fail if both X and Y are null values. Using the
== nullpart (with a literal null) forces a conversion toISNULLor whatever the SQL equivalent is.I agree it’s a pain, and someone else may have a better workaround, but this may help you get going.