【问题标题】:LinqKit PredicatesLinqKit 谓词
【发布时间】:2015-04-29 05:01:33
【问题描述】:

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

【问题讨论】:

    标签: predicates linqkit


    【解决方案1】:

    如果您只评估And 条件,则必须以True 谓词开头,主要是因为false &amp;&amp; bool1 &amp;&amp; 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 2017-09-26
      • 1970-01-01
      • 1970-01-01
      • 2015-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多