c# - 在 linq 查询中处理 Nullable bool
问题描述
我有一种情况,我将可为空的布尔值传递给方法,然后在 linq 查询中,如果该参数为空,那么我需要获取所有记录,否则进行比较并返回相对值。
这是我尝试过的(简化只问相关问题的方法)
public List<Something> Fetch(bool? allocated = null){
return (from x in DbContext.Something
where x.Active && (allocated == null || x.Allocated == allocated.Value)
select x).ToList();
}
我也检查过,allocated.HasValue
但每次都会出现同样的问题。
我得到的例外是:
System.InvalidOperationException: '可空对象必须有一个值。'
解决方案
我还不清楚为什么会失败,但是当我遇到这样的问题时,我倾向于尝试简化查询。特别是,“表达式树到 SQL”转换代码要做的工作越少,它就越有可能工作。
鉴于allocated == null
在查询过程中不会改变,我很想将代码更改为仅有条件地查询该部分。
public List<Something> Fetch(bool? allocated = null)
{
var query = DbContext.Something.Where(x => x.Active);
if (allocated != null)
{
// Do this outside the lambda expression, so it's just bool in the expression tree
bool allocatedValue = allocated.Value;
query = query.Where(x => x.Allocated == allocatedValue);
}
return query.ToList();
}
推荐阅读
- bash - 当使用 while read 行将一个文件的内容重定向到另一个文件时,它只显示数字“2”
- c++ - C++ std::bind() 成员函数的参数
- google-sheets - 如何使用只占用一列的连接重复多列查询 N 次?
- json - 如何在Scala中将Json DataFrame数组拆分为多个可能的行数
- django - Django 视图:postgres 物化视图可通过 get 但不能通过过滤器访问(两个查询集)
- sql - 带有循环的 PowerShell 脚本在加密后无法工作
- python - 寻找 DF1 和 DF2 之间的匹配,而不为 DF1 中的每一行循环
- java - 无法使用 LDAP 连接从 Java 后端检索 Active Directory 用户 [LDAP:错误代码 32 – 无此类对象]
- reactjs - 将时间戳转换为日期和时间(带时区)的任何解决方案?在 React.js 中
- r - 通过单个变量对数据框进行增量分箱,同时对所有其他变量取平均值