使用“where”方法调用表达式

时间:2014-09-13 18:34:36

标签: c# entity-framework system.reflection

我正在尝试实现这种表达:“A => ABWhere(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);

如何正确调用

1 个答案:

答案 0 :(得分: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));

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