首页 > 解决方案 > 在 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: '可空对象必须有一个值。'

标签: c#linq

解决方案


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

推荐阅读