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.Expression
1[System.Func
2[Class1]]' cannot be used for parameter of type 'Class2' of method 'System.Linq.IQueryable1[Class2] Select[Class1,Class2](System.Linq.IQueryable
1[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) }));
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) });