将expression参数作为参数传递给另一个表达式

Jer*_*ren 8 c# lambda expression entity-framework expression-trees

我有一个筛选结果的查询:

public IEnumerable<FilteredViewModel> GetFilteredQuotes()
{
    return _context.Context.Quotes.Select(q => new FilteredViewModel
    {
        Quote = q,
        QuoteProductImages = q.QuoteProducts.SelectMany(qp => qp.QuoteProductImages.Where(qpi => q.User.Id == qpi.ItemOrder))
    });
}
Run Code Online (Sandbox Code Playgroud)

在where子句中,我使用参数q将属性与参数qpi中的属性进行匹配.因为过滤器将在几个地方使用,我正在尝试将where子句重写为表达式树,它看起来像这样:

public IEnumerable<FilteredViewModel> GetFilteredQuotes()
{
    return _context.Context.Quotes.Select(q => new FilteredViewModel
    {
        Quote = q,
        QuoteProductImages = q.QuoteProducts.SelectMany(qp => qp.QuoteProductImages.AsQueryable().Where(ExpressionHelper.FilterQuoteProductImagesByQuote(q)))
    });
}
Run Code Online (Sandbox Code Playgroud)

在此查询中,参数q用作函数的参数:

public static Expression<Func<QuoteProductImage, bool>> FilterQuoteProductImagesByQuote(Quote quote)
{
    // Match the QuoteProductImage's ItemOrder to the Quote's Id
}
Run Code Online (Sandbox Code Playgroud)

我该如何实现这个功能?或者我应该使用不同的方法吗?

MBo*_*ros 9

如果我理解正确,你想在另一个中重用一个表达式树,并且仍然允许编译器为你构建表达式树.

这实际上是可能的,我已经在很多场合做过了.

诀窍是将可重用部分包装在方法调用中,然后在应用查询之前将其解包.

首先,我将更改获取可重用部分的方法作为返回表达式的静态方法(如mr100建议的那样):

 public static Expression<Func<Quote,QuoteProductImage, bool>> FilterQuoteProductImagesByQuote()
 {
     return (q,qpi) => q.User.Id == qpi.ItemOrder;
 }
Run Code Online (Sandbox Code Playgroud)

包装将通过以下方式完成:

  public static TFunc AsQuote<TFunc>(this Expression<TFunc> exp)
  {
      throw new InvalidOperationException("This method is not intended to be invoked, just as a marker in Expression trees!");
  }
Run Code Online (Sandbox Code Playgroud)

然后展开会发生在:

  public static Expression<TFunc> ResolveQuotes<TFunc>(this Expression<TFunc> exp)
  {
      var visitor = new ResolveQuoteVisitor();
      return (Expression<TFunc>)visitor.Visit(exp);
  }
Run Code Online (Sandbox Code Playgroud)

显然,最有趣的部分发生在访客身上.你需要做的是找到对你的AsQuote方法进行方法调用的节点,然后用lambdaexpression的主体替换整个节点.lambda将是该方法的第一个参数.

您的resolveQuote访客看起来像:

    private class ResolveQuoteVisitor : ExpressionVisitor
    {
        public ResolveQuoteVisitor()
        {
            m_asQuoteMethod = typeof(Extensions).GetMethod("AsQuote").GetGenericMethodDefinition();
        }
        MethodInfo m_asQuoteMethod;
        protected override Expression VisitMethodCall(MethodCallExpression node)
        {
            if (IsAsquoteMethodCall(node))
            {
                // we cant handle here parameters, so just ignore them for now
                return Visit(ExtractQuotedExpression(node).Body);
            }
            return base.VisitMethodCall(node);
        }

        private bool IsAsquoteMethodCall(MethodCallExpression node)
        {
            return node.Method.IsGenericMethod && node.Method.GetGenericMethodDefinition() == m_asQuoteMethod;
        }

        private LambdaExpression ExtractQuotedExpression(MethodCallExpression node)
        {
            var quoteExpr = node.Arguments[0];
            // you know this is a method call to a static method without parameters
            // you can do the easiest: compile it, and then call:
            // alternatively you could call the method with reflection
            // or even cache the value to the method in a static dictionary, and take the expression from there (the fastest)
            // the choice is up to you. as an example, i show you here the most generic solution (the first)
            return (LambdaExpression)Expression.Lambda(quoteExpr).Compile().DynamicInvoke();
        }
    }
Run Code Online (Sandbox Code Playgroud)

现在我们已经走了一半.如果你的lambda上没有任何参数,上面就足够了.在你的情况下,你想要实际将lambda的参数替换为原始表达式中的参数.为此,我使用了invoke表达式,在那里我得到了我想要在lambda中拥有的参数.

首先,我们创建一个访问者,它将使用您指定的表达式替换所有参数.

    private class MultiParamReplaceVisitor : ExpressionVisitor
    {
        private readonly Dictionary<ParameterExpression, Expression> m_replacements;
        private readonly LambdaExpression m_expressionToVisit;
        public MultiParamReplaceVisitor(Expression[] parameterValues, LambdaExpression expressionToVisit)
        {
            // do null check
            if (parameterValues.Length != expressionToVisit.Parameters.Count)
                throw new ArgumentException(string.Format("The paraneter values count ({0}) does not match the expression parameter count ({1})", parameterValues.Length, expressionToVisit.Parameters.Count));
            m_replacements = expressionToVisit.Parameters
                .Select((p, idx) => new { Idx = idx, Parameter = p })
                .ToDictionary(x => x.Parameter, x => parameterValues[x.Idx]);
            m_expressionToVisit = expressionToVisit;
        }

        protected override Expression VisitParameter(ParameterExpression node)
        {
            Expression replacement;
            if (m_replacements.TryGetValue(node, out replacement))
                return Visit(replacement);
            return base.VisitParameter(node);
        }

        public Expression Replace()
        {
            return Visit(m_expressionToVisit.Body);
        }
    }
Run Code Online (Sandbox Code Playgroud)

现在我们可以返回到ResolveQuoteVisitor,并正确地进行调用:

        protected override Expression VisitInvocation(InvocationExpression node)
        {
            if (node.Expression.NodeType == ExpressionType.Call && IsAsquoteMethodCall((MethodCallExpression)node.Expression))
            {
                var targetLambda = ExtractQuotedExpression((MethodCallExpression)node.Expression);
                var replaceParamsVisitor = new MultiParamReplaceVisitor(node.Arguments.ToArray(), targetLambda);
                return Visit(replaceParamsVisitor.Replace());
            }
            return base.VisitInvocation(node);
        }
Run Code Online (Sandbox Code Playgroud)

这应该做所有的技巧.你会用它作为:

  public IEnumerable<FilteredViewModel> GetFilteredQuotes()
  {
      Expression<Func<Quote, FilteredViewModel>> selector = q => new FilteredViewModel
      {
          Quote = q,
          QuoteProductImages = q.QuoteProducts.SelectMany(qp => qp.QuoteProductImages.Where(qpi => ExpressionHelper.FilterQuoteProductImagesByQuote().AsQuote()(q, qpi)))
      };
      selector = selector.ResolveQuotes();
      return _context.Context.Quotes.Select(selector);
  }
Run Code Online (Sandbox Code Playgroud)

当然,我认为你可以在这里提供更多的可重用性,甚至可以在更高的层次上定义表达式.

您甚至可以更进一步,在IQueryable上定义ResolveQuotes,只需访问IQueryable.Expression并使用原始提供程序和结果表达式创建新的IQUeryable,例如:

    public static IQueryable<T> ResolveQuotes<T>(this IQueryable<T> query)
    {
        var visitor = new ResolveQuoteVisitor();
        return query.Provider.CreateQuery<T>(visitor.Visit(query.Expression));
    }
Run Code Online (Sandbox Code Playgroud)

这样,您可以内联表达式树的创建.你甚至可以去覆盖ef的默认查询提供程序,并为每个执行的查询解析引号,但这可能会走得太远:P

您还可以看到这将如何转换为实际上任何类似的可重用表达式树.

我希望这有帮助 :)

免责声明:切记不要将粘贴代码从任何地方复制到生产中,而不了解它的作用.我没有在这里包含很多错误处理,以保持代码最小化.如果他们编译,我也没有检查使用你的类的部分.我也不对此代码的正确性承担任何责任,但我认为解释应该足够,以了解正在发生的事情,并在有任何问题时修复它.还要记住,这只适用于具有生成表达式的方法调用的情况.我将很快写一篇基于这个答案的博客文章,这也允许你在那里使用更多的灵活性:P

  • 这篇文章真的很老了,你应该试试 LinqKit,一个可以开箱即用的工具 (2认同)