This is very bizarre.
The following code throws a Object reference not set to an instance of an object
:
var members = db.Members.Where(
a =>
String.IsNullOrEmpty(searchEmail)
|| (a.Email ?? "").ToUpper().Contains(searchEmail.ToUpper()));
where db
is a DataContext
and searchEmail
is a string, which in this case is set to null
.
The code should return all Members
because the first half of the ||
returns true, however, I am getting the above exception.
Strangely if I change the code to:
var members = db.Members.Where(
a =>
String.IsNullOrEmpty(searchEmail)
|| (a.Email ?? "").ToUpper().Contains((searchEmail ?? "").ToUpper()));
no exception is thrown! Presumably that means that String.IsNullOrEmpty
is evaluating false
when clearly it is evaluating true
unless there is something about IQueryable
's implementation of Where
?
Update
Habib's answer is correct. For other people reading this, my solution to get around the limitation Habib explained was:
var members = db.Members.AsQueryable();
if (!String.IsNullOrEmpty(searchEmail))
members = members.Where(a => a.Email.ToUpper()
.Contains(searchEmail.ToUpper()));