C # expression casting as a derived type

Using

IQueryable<T> query - where T : BaseEntity

I have the following code used in a generic method that uses reflection to call the Where () method (this works):

var predicate = Expression.Lambda(body, item);
MethodInfo whereCall = (typeof(Queryable).GetMethods().First(mi => mi.Name == "Where" && mi.GetParameters().Length == 2).MakeGenericMethod(query.ElementType));
MethodCallExpression call = Expression.Call(whereCall, new Expression[] { query.Expression, predicate });

query = query.Provider.CreateQuery<T>(call);

I would like to use something like this (and avoid reflection):

var predicate = Expression.Lambda<Func<T, bool>>(body, item);
query = query.Where(predicate);

But the problem with this code is that T is used as a base type, not a derived type at runtime.

How can I use T as query.ElementType (derived type)?

+4
source share
1 answer

Your second part of the code is really better than the first. You will need to call the method Expression.Lambdausing reflection somehow. A convenient way to do this:

static IQueryable<T> CreateQuery<T>(IQueryable<T> query, ...) {
  var predicate = Expression.Lambda<Func<T, bool>>(body, item);
  query = query.Where(predicate);
  return query;
}

, T . , MakeGenericMethod. :

CreateQuery((dynamic)query);
+2

Source: https://habr.com/ru/post/1628702/


All Articles