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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With