Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two linq expressions to inject navigation property

I have identical set of conditions that are applied to one class directly or to some other class having same navigation property.

For example, I have home and I have agent, agent is associated with home.

So I am looking for a home with an agency name 'a', or I am looking for agent with name 'a', queries are as follow,

 Expression<<Func<Agent,bool>> ax = x=> x.Name == "a" ;

 Expression<Func<Home,bool>> hx = x=> x.Agent.Name == "a";

I have nearly 100 search queries for Agent, and I have to also apply them to Home queryable as well. I dont mind writing all again, but its difficult to maintain as we know they will change frequently during course of development.

What I want to do is, I want to compose expression for Home query like this,

 Expression<Func<Home,bool>> hx = Combine( x=>x.Agent , x=>x.Name == "a");

Where Combine will be following,

 Expression<Func<T,bool>> Combine<T,TNav>( 
     Expression<Func<T,TNav>> parent, 
     Expression<Func<TNav,bool>> nav){

     // combine above to form...


     (x=>x.Agent , x=>x.Name == "a") 
         => x => x.Agent.Name == "a"

     (x=>x.Agent, x=>x.Name.StartsWith("a") || x.Name.EndsWith("a"))
         => x=>x.Agent.Name.StartsWith("a") || x.Agent.Name.EndsWith("a")

     // look carefully, x gets replaced by x.Agent in every node..

     // I know very little about expression rewriting, so I need little help
 }
like image 466
Akash Kava Avatar asked Jun 05 '12 14:06

Akash Kava


1 Answers

Yes, you do need a visitor to replace parts of the original expressions. You could do something like that:

Expression<Func<T,bool>> Combine<T,TNav>(Expression<Func<T,TNav>> parent, Expression<Func<TNav,bool>> nav)
{
     var param = Expression.Parameter(typeof(T), "x");
     var visitor = new ReplacementVisitor(parent.Parameters[0], param);
     var newParentBody = visitor.Visit(parent.Body);
     visitor = new ReplacementVisitor(nav.Parameters[0], newParentBody);
     var body = visitor.Visit(nav.Body);
     return Expression.Lambda<Func<T, bool>>(body, param);
}

public class ReplacementVisitor : System.Linq.Expressions.ExpressionVisitor
{
    private readonly Expression _oldExpr;
    private readonly Expression _newExpr;
    public ReplacementVisitor(Expression oldExpr, Expression newExpr)
    {
        _oldExpr = oldExpr;
        _newExpr = newExpr;
    }

    public override Expression Visit(Expression node)
    {
        if (node == _oldExpr)
            return _newExpr;
        return base.Visit(node);
    }

}

Example usage:

Expression<Func<Foo, Bar>> expr1 = f => f.Bar;
Expression<Func<Bar, bool>> expr2 = b => b.Baz;
var expr = Combine(expr1, expr2); // f => f.Bar.Baz
like image 108
Thomas Levesque Avatar answered Sep 22 '22 14:09

Thomas Levesque