Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda Expressions and the || operator in Entity Framework

I was surprised that this code works:

string category = null;
Category Category = null;
int categoryId = 0;

var products = repository.Products
    .Where(p => category == null || p.CategoryID == categoryId)
    .ToList();

yet the code below fails:

string category = null;
Category Category = null;
int categoryId = 0;

var products = repository.Products
    .Where(p => category == null || p.CategoryID == Category.CategoryID)
    .ToList();

I know the issue is that even though I'm using the || operator-- it doesn't quite work as I would think it would.

In the second example Why does Category get looked at-- even though the category value is null. Wouldn't it get short circuited?

like image 453
ek_ny Avatar asked May 16 '13 20:05

ek_ny


1 Answers

Your "OR" is being sent to the database as SQL. Entity Framework has to evaluate Category in order to construct the proper SQL that gets sent to the database. In your first example, you didn't give Entity Framework that same problem. It's not a matter of short-circuiting, it's a matter of translating your expression (which includes the OR) into the proper query.

To be clear: if your query were happening in memory in Linq-to-Objects (as an example), your expectation that it could short-circuit and avoid dereferencing null would be correct. But it is not. The entire expression is being translated to SQL, which means it needs to evaluate Category (which you have initialized to null) to obtain the CategoryID, and your problem arises.

like image 180
Anthony Pegram Avatar answered Nov 15 '22 08:11

Anthony Pegram