简体   繁体   中英

C# Expression Casting as Derived Type

Using

IQueryable<T> query - where T : BaseEntity

I have the following code, used in a generic method - which uses reflection to call the .Where() method (this is working):

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 the base-type, and not the derived-type at run-time .

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

Your second piece of code is indeed better than the first one. You will need to invoke the Expression.Lambda method using reflection somehow . A convenient way to do that is this:

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

Invoke this method using T as the derived type. You can perform that call using MakeGenericMethod . Depending on your scenario it might be enough to say:

CreateQuery((dynamic)query);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM