When I use a null coalescing operator in the “.Where” section of a linq statement, it’s not working as intended.
Here’s the offending code: (Note that the TotalBalance is of type nullable decimal.)
Account.Where(n => (n.TotalBalance ?? 0) != 0)
.Select(n => new { n.AccountId, n.TotalBalance })
The result includes accounts whose TotalBalance is null:
Checking the SQL generated by LINQ to SQL, I can see the problem:
SELECT [n].[AccountID], [n].[TotalBalance]
FROM [Account] AS [n]
WHERE (COALESCE([n].[TotalBalance], 0.0) <> 0.0) OR [n].[TotalBalance] IS NULL
Why is LINQ to SQL inserting the condition OR [n].[TotalBalance] IS NULL
?
If I remove the null coalesce from the linq statement, the results are correct:
Account.Where(n=>n.TotalBalance != null && n.TotalBalance != 0)
.Select(n => new { n.AccountId, n.TotalBalance })
Using EF Core version 2.2.6 (yes, I know it’s deprecated. Is that a known bug that was fixed?)