In such a code:
if (insuranceNumberSearch == null
? true
: ei.InsuranceNumber.Contains(insuranceNumberSearch.Trim()))
doSomething();
where insuranceNumberSearch
is null, remaining expression is not null while in following code:
var q = from ei in session.Linq<EmployeeInsurance>()
where insuranceNumberSearch == null
? true
: ei.InsuranceNumber.Contains(insuranceNumberSearch.Trim())
select ei;
all section of expression is evaluated regardless of insuranceNumberSearch is null or is not null.
I'm using LINQ to NHibernate
UPDATE:
Unfortunately I have put the first snippet wrong. The correct is:
if (insuranceNumberSearch == null || (insuranceNumberSearch != null && ei.InsuranceNumber.Contains(insuranceNumberSearch.Trim()))
doSomething();
or
bool b1 = insuranceNumberSearch == null ? true : ei.InsuranceNumber.Contains(insuranceNumberSearch.Trim());
if (b1)
doSomething();
In both of above when insuranceNumberSearch
is null
, remaining expressions are not evaluated any more. If such a behavior does not exists, insuranceNumberSearch.Trim()
will cause a reference object is null exception. Sadly LINQ (or maybe LINQ-to-NHibernate) does not obey such a nice behavior and evaluate all of expression even when insuranceNumberSearch
is null
and results in error.
UPDATE 2: I found a similar question: http://stackoverflow.com/questions/772261/the-or-operator-in-linq-with-c