【发布时间】:2016-03-13 00:19:25
【问题描述】:
类测试器正在尝试对通用可查询对象调用 sum。它在 MethodCallExpression 上中断。所以我不确定下面的行是否真的会运行。
我也尝试过在单独的调用中获取 MethodInfo,但它总是返回 null。所以我相信用我提供的参数找到“Sum”函数是个麻烦。任何帮助是极大的赞赏。
class test
{
public int sumMe { get; set; }
}
[TestMethod]
public void foo()
{
var list = new List<test>();
list.Add(new test() { sumMe = 1 });
list.Add(new test() { sumMe = 2 });
list.Add(new test() { sumMe = 3 });
tester.run(list.AsQueryable(), "sumMe");
}
class tester
{
public static void run<TSource>(IQueryable<TSource> source, string field)
{
ParameterExpression instance = Expression.Parameter(typeof(TSource), "x");
MemberExpression propertyOnInstance = Expression.PropertyOrField(instance, field);
Type typeOfGenericFunction = typeof(Func<,>).MakeGenericType(typeof(TSource), typeof(int));
LambdaExpression lambda = Expression.Lambda(typeOfGenericFunction, propertyOnInstance, instance);
MethodCallExpression expr = Expression.Call(typeof(Queryable), "Sum", new Type[] { typeof(TSource) }, propertyOnInstance, lambda);
var hopingThisWorks = source.Provider.CreateQuery<TSource>(expr);
}
}
【问题讨论】:
标签: c# entity-framework generics lambda expression