我试图弄清楚谓词是如何工作的。我有一段代码,其中始终提供一个参数,但最多可能有 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 的秘诀是什么。