I'm trying to use Linq to SQL to filter a table with a nullable bool value based on a variable.
But if the variable's value is NULL, LINQ seems to translate the query to Field = NULL
instead of Field IS NULL
.
Based on other posts I've seen to use object.Equals
to map correctly. And that works, but only when the variable's value is null.
Sample code:
bool? relevantValue = null;
var q = from m in MyTable
where ???
select m;
Case 1:
If where clause is object.Equals(m.IsRelevant, relevantValue)
, it works when relevantValue
is null and true, but returns incorrect results when relevantValue
= false.
It translates in SQL to
WHERE ( (CASE WHEN [t0].[IsRelevant] = 1 THEN 1 ELSE 0 END)) = 0
Case 2:
For where (relevantValue == null ? object.Equals(m.IsRelevant, relevantValue) : m.IsRelevant == relevantValue)
it works for relevantValue
= true or false, but when null gives an error that:
The argument 'value' was the wrong type. Expected 'System.Boolean'. Actual 'System.Nullable`1[System.Boolean]'.
Do I have other options that will work for null, true and false?