PredicateBuilder剥离括号,打破嵌套的AND与OR结合

时间:2013-11-19 04:59:35

标签: c# .net linq predicatebuilder

如何使用PredicateBuilder将几个语句与嵌套的AND组合在一起,而不用去掉括号?

我们正试图获得:

(fieldA = X AND fieldB = Y AND fieldC = Z)  or (fieldA = A AND fieldB = B and fieldC = C)

但下面的代码生成(注意没有括号,意味着DB查询返回错误的数据)

fieldA = X AND fieldB = Y AND fieldC = Z  or fieldA = A AND fieldB = B and fieldC = C

我们正在构建这样的谓词:

var predicate = PredicateBuilder.False<MonitoredService>();

foreach (var a in affected)
{
    var a1 = a;
    predicate = predicate.Or(m => m.ItemId == a1.ItemId && m.MinSeverity <= a1.Severity && m.LastUpdatedUtc <= a1.LastModifiedUtc);
}

var monitors = _monitoredServiceRepository.List(predicate);

1 个答案:

答案 0 :(得分:1)

在LINQ和SQL Server中(并且我很肯定这也是MySQL,Oracle和其他DB的情况),在OR运算符之前首先评估AND运算符。

所以

(fieldA = X AND fieldB = Y AND fieldC = Z)  or (fieldA = A AND fieldB = B and fieldC = C)

相同
fieldA = X AND fieldB = Y AND fieldC = Z  or fieldA = A AND fieldB = B and fieldC = C