【问题标题】:Expression with "where" method invoking使用“where”方法调用的表达式
【发布时间】:2014-09-14 04:08:36
【问题描述】:

我正在尝试实现这种表达式:“A => A.B.Where(extExp).Count() > 0”并且我遇到了如何为 Where(...) 进行表达式的问题因为我假设 ICollection 的扩展方法。有人可以帮忙吗?

Expression<Func<N, bool>> conditions = c => c.T_ID == 1 || c.T_ID == 2;
ParameterExpression mpe = Expression.Parameter(typeof(T), "A");
Expression prop = Expression.Property(mpe,typeof(T).GetProperty("B"));
...
var propWhere = Expression.Call(..., prop, conditions);

如何正确调用

【问题讨论】:

    标签: c# entity-framework system.reflection


    【解决方案1】:

    那里有一个使用 MethodInfo 的调用的重载。要获取方法信息,我认为最好使用此答案中的代码 - https://stackoverflow.com/a/21060046/122507

    public static MethodInfo GetMethodInfo(Expression<Action> expression)
    {
        var member = expression.Body as MethodCallExpression;
    
        if (member != null)
            return member.Method;
    
        throw new ArgumentException("Expression is not a method", "expression");
    }
    

    用法

    var whereMethodInfo = GetMethodInfo(() => Enumerable.Where(Enumerable.Empty<T>(), i=>true));
    

    顺便说一句,我建议您下载 LINQPad 并使用它来编写查询并查看生成的表达式树和 IL 代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-02
      • 1970-01-01
      相关资源
      最近更新 更多