gpt4 book ai didi

c# - LinqToSql 查询中的条件快捷方式

转载 作者:太空狗 更新时间:2023-10-29 22:35:13 24 4
gpt4 key购买 nike

这里有一些 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 to sql,请记住 Linq 只是将您的查询解析为 SQL。

因此,它将您的两个 where 子句发送到数据库,因此出现异常。我真的不觉得这令人惊讶,尽管它可以说是错误的。

您只需进行独立检查。

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

关于c# - LinqToSql 查询中的条件快捷方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1855056/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com