开发者

Invoke a C# inner Expression with a member property of a parameter to an outer expression

I am using the Albaharis PredicateBuilder as found here http://www.albahari.com/nutshell/predicatebuilder.aspx to filter results in a Linq-to-SQL application. This has been working great.

What I am trying to do now, is reuse the existing filtering predicate expression to filter an object that has the existing开发者_Python百科 filtered object as a property.

For example, I have 2 classes, Order and Customer. I already have a method that returns a Expression<Func<Customer, bool>>, which is built using the above mentioned predicate builder. I now want to reuse this in my Order filtering method, which will return a Expression<Func<Customer, bool>> by somehow passing the Order.Customer property (expression?) into my Customer filter method.

I have something like this (far from complete, but I hope you get the idea):

public class CustomerSearchCriteria
{
    public Expression<Func<Customer, bool>> FilterPredicate()
    {
        // Start with predicate to include everything
        var result = PredicateBuilder.True<Customer>();

        // Build predicate from criteria
        if (!String.IsNullOrEmpty(this.Name))
        {
            result = result.And(c => SqlMethods.Like(c.Name, this.Name));
        }

        // etc. etc. etc

} 


public class OrderSearchCriteria
{
    public Expression<Func<Order, bool>> FilterPredicate()
    {
        // Start with predicate to include everything
        var result = PredicateBuilder.True<Order>();

        // Build predicate from criteria
        if (!String.IsNullOrEmpty(this.Reference))
        {
            result = result.And(o => SqlMethods.Like(o.Reference, this.Reference));
        }

        // etc. etc. etc
        // This is where I would like to do something like:
        // result = result.And(o => o.Customer "matches" this.CustomerCriteria.FilterPredicate()
} 

Can any Linq expression guru help me?

Thanks in advance.


If you use the Albaharis' LinqKit, you should be able to do something like this:

var customerFilter = this.CustomerCriteria.FilterPredicate();
// create an expression that shows us invoking the filter on o.Customer
Expression<Func<Order, bool>> customerOrderFilter = 
    o => customerFilter.Invoke(o.Customer);
// "Expand" the expression: this creates a new expression tree
// where the "Invoke" is replaced by the actual predicate.
result = result.And(customerOrderFilter.Expand())
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜