我正在试图弄清楚谓词是如何工作的。我有一段代码,其中将始终提供一个参数,但可能有多达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
我正在努力弄清楚如何使它工作,因为总有一段时间所有参数都是可选的。我将无法使用.Or,让.And工作的秘诀是什么,不管增加了多少参数。
发布于 2015-04-28 20:59:45
如果只计算And条件,则必须从True谓词开始,主要是因为false && bool1 && bool2 ...总是计算为false。
var predicate = PredicateBuilder.True<Data.AccountAllocation>();但是,当谓词链中有一个Or谓词时,如果Or谓词的计算结果为true,则表达式将变为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);https://stackoverflow.com/questions/29928352
复制相似问题