条件的快捷方式
问题描述:
这里有一个小LinqToSql疑难杂症:条件的快捷方式
// 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();
}
你猜怎么着 - 如果你传递一个空State
对象这种方法,你会得到一个空引用异常!看来LinqToSql并不使用||
快捷键作为快捷键!
回答信贷去谁建议最好的解释&解决方法为此。
答
如果它是LINQ到SQL,那么记住Linq只是将你的查询解析成SQL。
因此,它将两个where子句发送到数据库,因此是例外。我真的没有发现这种令人惊讶的事情,尽管它可能是错误的。
你只需要做一个独立的检查。
if (!string.isNullOrEmpty(state.statecode)
q = q.where(s => s.code == state.statecode
+0
+1我喜欢使用拉姆达添加到查询的想法。 – 2009-12-06 12:10:11
答
这与LINQ一般无关。在这种情况下,LINQ-to-SQL提供程序试图解析您的lambda表达式并将其设置为TSQL查询。它不能根据您的表达,因为它试图大部分工作委托给数据库太多的假设。
长话短说,供应商根本无法将其翻译成SQL。
这是LinqToSql? – 2009-12-06 11:26:31
在'正常'Linq类似的查询适合我。 – 2009-12-06 11:57:25
是的,这是LinqToSql - 对不起,将编辑的问题 – 2009-12-06 12:07:51