Using: Entity Framework 4.3.1, MVC 4
Sample database records (for example):
Id Height 1 null 2 2.1
Why does this first statement bring back zero results:
decimal? scannedItemHeight = default(decimal?);
(from st in Stocks
where st.Height == scannedItemHeight
select st.Id).ToList();
But this statement returns record Id 1:
(from st in Stocks
where st.Height == null
select st.Id).ToList();
If scannedItemHeight is null, I only want to match values where the height is null too.
I only want to return the first record, Id 1.
UPDATE I ended up using:
st.Height == scannedItemHeight || (scannedItemHeight == null && st.Height == null)
I've certainly seen some odd LINQ behaviour before now, due to the way that SQL handles nulls not being the same as the way that C# handles nulls. In C#, a == b
is true if a
and b
are both null, whereas in SQL they're not... instead you have to deliberately check for nullity. I would try:
var temp = (from st in Stocks
where st.Height == scannedItemHeight || (scannedItemHeight == null && st.Height == null)
select st.Id).ToList();
Or construct the queries differently:
var filtered = scannedItemHeight == null
? Stocks.Where(st => st.Height == null)
: Stocks.Where(st => st.Height == scannedItemHeight);
var temp = filtered.Select(st => st.Id).ToList();
See more on this question at Stackoverflow