在linq查询中处理可空布尔

Ahm*_*mad 2 c# linq

我有一种情况,我将可为空的布尔值传递给该方法,然后在linq查询中,如果该参数为null,则需要获取所有记录,否则进行比较并返回相对值。

这是我尝试过的方法(简化了仅询问相关问题的方法)

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();
}
Run Code Online (Sandbox Code Playgroud)

我也检查过,allocated.HasValue但是每次都出现相同的问题。

我得到的异常是:

System.InvalidOperationException:'空对象必须具有一个值。

Jon*_*eet 9

我尚不清楚为什么会失败,但是当遇到此类问题时,我倾向于尝试简化查询。特别是,“表达式树到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();
}
Run Code Online (Sandbox Code Playgroud)