构建一个定制的谓语使用foreach循环来充当过滤器 [英] Building a custom predicate to act as a filter using a foreach loop

查看:262
本文介绍了构建一个定制的谓语使用foreach循环来充当过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要把它们传递给我挣扎到自定义过滤器过滤的文件清单建立动态使用的foreach 循环

I need to filter a list of documents by passing them to a custom filter that I'm struggling to build dynamically using a foreach loop :

var mainPredicate = PredicateBuilder.True<Document>();

// mainPredicate is combined to other filters successfully here ...

var innerPredicate = PredicateBuilder.False<Document>();
foreach (var period in periods)
{
    var p = period;
    Expression<Func<Document, bool>> inPeriod =
        d => d.Date >= p.DateFrom && d.Date <= p.DateTo;

    innerPredicate = innerPredicate.Or(d => inPeriod.Invoke(d));
}

mainPredicate = mainPredicate.And(innerPredicate);

这最后一行:

documents = this.ObjectSet.AsExpandable().Where(mainPredicate).ToList();



抛出此异常:

Throws this exception :

参数D未在指定的LINQ势必实体
查询表达式。

任何人都知道,为什么我得到这个例外?我不明白的地方,我传递给InPeriod方法'D'参数丢失。我不知道什么是缺少这个工作。我的代码是一样的许多其他的工作完美的例子。有关调用表达式和它是如何工作在幕后,欢迎任何其它附加单位理论单位理论信息。

Anyone knows why I'm getting this exception ? I don't understand where the 'd' parameter I am passing to the InPeriod method gets lost. I don't know what is missing for this to work. My code is the same as many other examples that work perfectly. Any additionnal theoric theoric information about invoking expressions and how it works behind the scenes are welcome.

推荐答案

最后,我已经找到了一种方法避免多个谓词合并到主表达式树。

Finally, I have found a way to avoid combining multiple predicates to the main expression tree.

由于每个谓词代表了不同的过滤器,我想最终,结合过滤器是一系列的必须待尊重的条件下,我们可以说,每个谓词必须返回真正作为最后的谓词返回true。

Given that each predicate represents a different filter and I want the final, combined filter to be a series of must-be-respected conditions, we can say that each of the predicates has to return true for the final predicate to return true.

有关的工作,谓词必须用相结合的 。因此,产生的SQL查询必须是这样的:

For that to work, the predicates has to be combined with AND. So, the resulting SQL query must look like this :

predicate1和predicate2和predicate3 ...

一个更好的办法来这些谓词与组合是链其中,查询运营商最终的查询,如:

A better way to combine these predicates with AND is to chain Where query operators to the final query, like this :

var documents = this.ObjectSet.AsExpandable()
    .Where(mainPredicate)
    .Where(otherPredicate)
    .Where(yetAnotherPredicate)
    .ToList();



产生的SQL查询将结合这些谓词与。这正是我想做的事。

The resulting SQL query will combine each of these predicates with AND. That is just what I wanted to do.

有比我自己出黑客表达式树更容易。

It is easier than hacking out an expression tree by myself.

这篇关于构建一个定制的谓语使用foreach循环来充当过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆