结合两个linq表达式来注入导航属性

时间:2012-06-05 14:03:40

标签: c# linq entity-framework lambda expression

我有一组相同的条件直接应用于一个类或具有相同导航属性的其他类。

例如,我有家,我有代理人,代理人与家庭有联系。

所以我正在寻找一个代理商名称为'a'的房子,或者我正在寻找名为'a'的代理商,查询如下,

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

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

我有近100个针对Agent的搜索查询,我还必须将它们应用于Home queryable。我不介意再写一遍,但它很难维护,因为我们知道它们会在开发过程中经常变化。

我想要做的是,我想为Home查询构建表达式,

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

如果要关注Combine,

 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
 }

2 个答案:

答案 0 :(得分:4)

是的,您确实需要访问者来替换部分原始表达式。你可以这样做:

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);
    }

}

使用示例:

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

答案 1 :(得分:0)

看看我对PredicateBuilder的观点,我认为它会帮助你。如果没有,请详细说明您的需求。 Dynamic Where condition with Queryover