【问题标题】:Linq-Sql IQueryable<T> and chaining OR operationsLinq-Sql IQueryable<T> 和链接 OR 操作
【发布时间】:2009-11-30 13:01:43
【问题描述】:

我正在尝试模拟:

在哪里 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 的另一个问题中所看到的那样。

【问题讨论】:

    标签: linq-to-sql iqueryable conditional-operator


    【解决方案1】:

    试试这个:

    qry = qry.Where(x => (onlyActiveItems
                          ? x.IsActive
                          : false) ||
                         (whenSpecifiedMustIncludeRecordWithThisId.HasValue
                          ? x.Id == whenSpecifiedMustIncludeRecordWithThisId
                          : false) ||
                         (!onlyActiveItems && !whenSpecifiedMustIncludeRecordWithThisId.HasValue));
    

    请注意,我们将int?int 进行比较,而不是两个ints。

    我在这里假设查询的目的是过滤掉是否满足某些条件。

    • 如果onlyActiveItems为真,则验证IsActive字段是否为真
    • 如果whenSpecifiedMustIncludeRecordWithThisId.HasValue 为真,则验证该值是否与Id 字段匹配
    • 如果两者都为真,则逻辑 OR 条件
    • 如果两者都为假,则显示所有记录(如果这不是本意,您可以删除最后一个条件)

    【讨论】:

    • 在int的情况下,我得到“Nullable object must have a value”?为空。
    • 试试这个修改后的解决方案
    • 仍然没有运气,我在想也许是其他原因造成的,但它非常不寻常
    • 对不起,逻辑有点倒退,这应该可以按预期工作。
    • 如果两者都为真,我已经对逻辑或条件进行了一些调整。
    【解决方案2】:

    使用“int?”时我通常使用 object.Equals(i1, i2) 来比较它们,例如

    from r in cxt.table
    where object.Equals(r.column, nullableInt)
    select r
    

    这避免了所有可以为空的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-02
      • 1970-01-01
      • 2017-02-22
      • 2019-11-21
      • 2020-05-27
      • 1970-01-01
      • 2011-02-15
      • 1970-01-01
      相关资源
      最近更新 更多