类型'System.Linq.Expressions.Expression的表达式不能用于类型的参数

时间:2015-01-27 16:22:24

标签: c# linq expression entity-framework-6

我为Type

创建了动态选择
public static IQueryable<TResult> Select<TSource, TResult>(this IQueryable<TSource> source, TResult result)
{
    var resultType = typeof(TResult);
    var resultObj = Expression.New(resultType);
    var receiverProperties = resultType.GetProperties();
    var sourceParameter = Expression.Parameter(typeof(TSource), "item");
    var resultParameters = new List<MemberBinding>();

    foreach (var receiverProperty in receiverProperties)
    {
        var sourceProperty = typeof(TSource).GetProperty(receiverProperty.Name);

        if (sourceProperty != null)
        {
            var sourcePropertyAccess = Expression.MakeMemberAccess(sourceParameter, sourceProperty);
            var memberInit = Expression.Bind(receiverProperty, sourcePropertyAccess);
            resultParameters.Add(memberInit);
        }
    }

    var selector = Expression.Lambda(Expression.MemberInit(resultObj, resultParameters), sourceParameter);

    return source.Provider.CreateQuery<TResult>(Expression.Call(
             null,
             ((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TResult)),
             new[] { source.Expression, Expression.Quote(selector) }));
}

但是这段代码返回异常

  

类型的表达   'System.Linq.Expressions.Expression 1[System.Func 2 [Class1]]'不能   用于方法类型'Class2'的参数   'System.Linq.IQueryable 1[Class2] Select[Class1,Class2](System.Linq.IQueryable 1 [Class1],Class2)

我需要转换?如果是 - 在哪里?

更新

我遇到错误

 return source.Provider.CreateQuery<TResult>(Expression.Call(
             null,
             ((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TResult)),
             new[] { source.Expression, Expression.Quote(selector) }));

1 个答案:

答案 0 :(得分:0)

行。我在问题上找到了答案。我们将调用生成方法的问题。

Expression.Call(
         null,
         ((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TResult)),
         new[] { source.Expression, Expression.Quote(selector) })

为了工作,我们需要使用

                Expression.Call(
                    typeof(Queryable),
                    "Select",
                    new Type[] { source.ElementType, selector.Body.Type },
                    new[] { source.Expression, Expression.Quote(selector) });
相关问题