Question

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()));
Was it helpful?

Solution

This LINQ expression translates in to SQL Query, it doesn't do short circuiting as expected. That is why you are getting th exception.

SQL-CLR Type Mismatches

C# specifies short circuit semantics based on lexical order of operands for logical operators && and ||. SQL on the other hand is targeted for set-based queries and therefore provides more freedom for the optimizer to decide the order of execution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top