1

我试图弄清楚谓词是如何工作的。我有一段代码,其中始终提供一个参数,但最多可能有 5 个不同的参数。

如果我尝试这种方式

var predicate = PredicateBuilder.False<Data.AccountAllocation>();                  

if (startDate.HasValue)
   predicate = predicate.And(p => p.DateEntered >= startDate);

if (endDate.HasValue)
   predicate = predicate.And(p => p.DateEntered <= endDate);

if (allocationTypeId.HasValue)
    predicate = predicate.And(p => p.AllocationTypeID == allocationTypeId);

if (allocationStatusID.HasValue)
    predicate = predicate.And(p => p.AllocationStatusTypeID == allocationStatusID);

var accountAllocation = await db.AccountAllocations.AsExpandable().Where(predicate).ToListAsync();

return accountAllocation;

如果我这样写,它什么也不返回

var predicate = PredicateBuilder.False<Data.AccountAllocation>();

if (accountId > 0)
   predicate = predicate.Or(p => p.AccountID == accountId);

if (startDate.HasValue)
   predicate = predicate.And(p => p.DateEntered >= startDate);

if (endDate.HasValue)
   predicate = predicate.And(p => p.DateEntered <= endDate);

if (allocationTypeId.HasValue)
   predicate = predicate.And(p => p.AllocationTypeID == allocationTypeId);

if (allocationStatusID.HasValue)
   predicate = predicate.And(p => p.AllocationStatusTypeID == allocationStatusID);

var accountAllocation = await db.AccountAllocations.AsExpandable().Where(predicate).ToListAsync();

return accountAllocation;

它工作正常。如果我将第一个谓词(帐户)从 .Or 更改为 .And 它不起作用。

.Or 似乎总是在运行,但如果我输入 .Or 对于所有这些,返回的日期是不正确的,因为它需要是一个 .And

我试图弄清楚如何让它工作,因为会有一段时间所有参数都是可选的。而且我将无法使用 . 或者,无论添加多少参数,获得 .And 的秘诀是什么。

4

1 回答 1

1

如果您只评估And条件,则必须从True谓词开始,基本上是因为false && bool1 && bool2 ...总是评估为false

var predicate = PredicateBuilder.True<Data.AccountAllocation>();

但是,当Or谓词链中有谓词时,表达式变为trueif 该Or谓词的计算结果为true

您可能从False谓词开始,因为您不想返回任何没有输入单个参数的数据。您可以通过检查最后的谓词来实现这一点:

var predicate = PredicateBuilder.True<Data.AccountAllocation>();
var initString = predicate.ToString();

if (startDate.HasValue)
   predicate = predicate.And(p => p.DateEntered >= startDate);

...

if (predicate.ToString() == initString)
    predicate = predicate.And(p => false);
于 2015-04-28T20:59:45.520 回答