Conditional shortcuts in LinqToSql query
c#, linq, linq-to-sql
Solution
If it's linq to sql then remeber that Linq is just parsing your query into SQL.
It is therefore sending both of your where clauses to the database, hence the exception. I dont find this surprising really, though it is arguably wrong.
You will just have to do an independant check.
if (!string.isNullOrEmpty(state.statecode)
q = q.where( s => s.code == state.statecode
Problem
Here's a little LinqToSql GOTCHA: ``` // Returns the number of counties in a state, // or all counties in the USA if the state is null public static int CountCounties(State s) { var q = from cy in County.GetTable() // my method to get the ITable where (s == null || s.Code == cy.StateCode) // shortcut OR operator, right...? select cy; return q.Count(); } ``` Guess what - if you pass a null `State` object to this method, you get a null reference exception! It seems that LinqToSql doesn't use the `||` shortcut operator as a shortcut! Answer credit goes to whoever proposes the best explanation & workaround for this.