Expression of type 'System.Linq.Expressions.Expression cannot be used for parameter of type

c# entity-framework-6 expression linq

Question

I created dynamic select for 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) }));
}

But this code return exception

Expression of type 'System.Linq.Expressions.Expression1[System.Func2[Class1]]' cannot be used for parameter of type 'Class2' of method 'System.Linq.IQueryable1[Class2] Select[Class1,Class2](System.Linq.IQueryable1[Class1], Class2)

Me need convertion? If yes - where?

Update

Error I get at

 return source.Provider.CreateQuery<TResult>(Expression.Call(
             null,
             ((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TResult)),
             new[] { source.Expression, Expression.Quote(selector) }));
1
0
1/27/2015 4:35:27 PM

Popular Answer

OK. I found answer at my question. It is problem with generation method witch we will call.

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

For work, we need using

                Expression.Call(
                    typeof(Queryable),
                    "Select",
                    new Type[] { source.ElementType, selector.Body.Type },
                    new[] { source.Expression, Expression.Quote(selector) });
0
1/30/2015 2:36:49 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow