LinqToSql查询中的条件快捷方式

Sha*_*ica 5 c# linq linq-to-sql

这里有一点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();
}
Run Code Online (Sandbox Code Playgroud)

猜猜看 - 如果你将null State对象传递给这个方法,你会得到一个空引用异常!似乎LinqToSql不使用||快捷操作符作为快捷方式!

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

Pau*_*sey 6

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

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

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

if (!string.isNullOrEmpty(state.statecode)
     q = q.where( s => s.code == state.statecode
Run Code Online (Sandbox Code Playgroud)