我正在尝试模拟:
其中 x.IsActive = true 或 x.Id = 5
以下导致使用“AND”...如何使用 IQueryable (qry) 和我的可为空的 int 模拟“OR”条件,因为此处可能涉及其他过滤,就像 IsActive 过滤器一样?
            if (onlyActiveItems) //bool
            {
                qry = qry.Where(x => x.IsActive == true);
            }
            if (whenSpecifiedMustIncludeRecordWithThisId.HasValue) //int?
            {
                qry = qry.Where(x => x.Id == whenSpecifiedMustIncludeRecordWithThisId.Value);
            }
我考虑过联合,但它的答案似乎应该简单得多。
这是一种解决方案,它解决了我在尝试组合所有答案时遇到的“可空对象必须具有值”的问题。是什么导致 nullable 在其他情况下为 null 时被评估?
            if (whenSpecifiedMustIncludeRecordWithThisId.HasValue)
            {
                qry = qry.Where(x => (!onlyActiveItems || (onlyActiveItems && x.IsActive)) || x.Id == whenSpecifiedMustIncludeRecordWithThisId.Value);
            }
            else
            {
                qry = qry.Where(x => (!onlyActiveItems || (onlyActiveItems && x.IsActive)));
            }
在某些情况下,使用 nullable 的 .Value 属性似乎也会有所不同,正如我在此处Linq to SQL Int16 Gets Converted as Int32 In SQL Command的另一个问题中所看到的那样