LinqToSql查询中的条件快捷方式 [英] Conditional shortcuts in LinqToSql query

查看:63
本文介绍了LinqToSql查询中的条件快捷方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有一些LinqToSql GOTCHA:

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();
}

猜猜是什么-如果将null State对象传递给此方法,则会得到null引用异常!看来LinqToSql没有使用||快捷方式运算符作为快捷方式!

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.

推荐答案

如果是sql的linq,请记住Linq只是将查询解析为SQL.

If it's linq to sql then remeber that Linq is just parsing your query into SQL.

因此它将两个where子句都发送到数据库,因此是异常.尽管可以说是错误的,但我并不觉得这确实令人惊讶.

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

这篇关于LinqToSql查询中的条件快捷方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆