LinqToSql查询中的条件快捷方式

这里有一点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(); } 

猜猜看 – 如果将null State对象传递给此方法,则会得到空引用exception! 似乎LinqToSql不使用|| 快捷操作符作为快捷方式!

答案可归功于为此提出最佳解释和解决方法的人。

如果它是linq to sql那么请记住Linq只是将你的查询解析为SQL。

因此,它将两个where子句发送到数据库,因此例外。 我真的没有发现这个令人惊讶的,尽管这可能是错误的。

你只需要做一个独立的检查。

 if (!string.isNullOrEmpty(state.statecode) q = q.where( s => s.code == state.statecode 

这与LINQ一般无关。 在这种情况下,LINQ-to-SQL提供程序尝试解析您的lambda表达式并使其成为TSQL查询。 它不能根据你的表达式做太多假设,因为它试图将大部分工作委托给数据库。

长话短说,提供者根本无法将其转换为SQL。