Expression.Call与泛型类型

时间:2016-03-13 00:19:25

标签: c# entity-framework generics lambda expression

类测试器试图在泛型可查询上调用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);

        }
    }

1 个答案:

答案 0 :(得分:-1)

你试过这个吗?

var sum = new Func<IQueryable<TSource>, Expression<Func<TSource, int>>, int>(Queryable.Sum).Method;