I’m trying to simulate:
WHERE x.IsActive = true OR x.Id = 5
The following causes ‘AND’ to be used… how do I simulate an ‘OR’ condition with IQueryable (qry) and my nullable int, given that other filtering might be involved as with the IsActive filter here?
if (onlyActiveItems) //bool
{
qry = qry.Where(x => x.IsActive == true);
}
if (whenSpecifiedMustIncludeRecordWithThisId.HasValue) //int?
{
qry = qry.Where(x => x.Id == whenSpecifiedMustIncludeRecordWithThisId.Value);
}
I have considered union but its seems the answer to this should be much simpler.
This is one solution which gets around the problem I get with “Nullable object must have a value” when trying the combined all in one answer. What causes the nullable to be evaluated when it is null otherwise?
if (whenSpecifiedMustIncludeRecordWithThisId.HasValue)
{
qry = qry.Where(x => (!onlyActiveItems || (onlyActiveItems && x.IsActive)) || x.Id == whenSpecifiedMustIncludeRecordWithThisId.Value);
}
else
{
qry = qry.Where(x => (!onlyActiveItems || (onlyActiveItems && x.IsActive)));
}
It seems also in some cases the use of the nullable’s .Value property makes a difference as seen in another question of mine here Linq to SQL Int16 Gets Converted as Int32 In SQL Command
Try this:
Note that we’re comparing an
int?to anint, not twoints.I am assuming here that the point of the query is to filter out if certain conditions are met.
onlyActiveItemsis true, it verifies whether the IsActive field is truewhenSpecifiedMustIncludeRecordWithThisId.HasValueis true it verifies whether the value matches the Id field