In this code:
if (insuranceNumberSearch == null ? true : ei.InsuranceNumber.Contains(insuranceNumberSearch.Trim())) doSomething();
where insuranceNumberSearch is null, the remaining expression is not null, but in the following code:
var q = from ei in session.Linq<EmployeeInsurance>() where insuranceNumberSearch == null ? true : ei.InsuranceNumber.Contains(insuranceNumberSearch.Trim()) select ei;
the entire expression section is evaluated regardless of the type of insurance NumberSearch is null or non-null.
I am using LINQ to NHibernate
UPDATE:
Unfortunately, I was mistaken in the first fragment. Right:
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 the above, when insuranceNumberSearch null , the remaining expressions are no longer evaluated. If this behavior does not exist, insuranceNumberSearch.Trim() will cause the referenced object to be a NULL exception. Sadly LINQ (or perhaps LINQ-to-NHibernate) does not obey this pleasant behavior and evaluates all expressions, even when insuranceNumberSearch is null and leads to an error.
UPDATE 2: I found a similar question: The || (or) Operator in Linq with C #
source share