MJM
MJM

Reputation: 431

Cast lambda expression to derived type

I need a little piece of magic. I believe what I am trying to do makes sense, but if it I've not seen a problem with the plan the reasons why would be just as welcome.

I have an expression

Expression<Func<Entity, bool>>

and I want to cast/convert or even create a whole new expression:

Expression<Func<Derived, bool>>

This is being used as an EF filter query, passed as an argument to a repository method. The repository returns an enumerable of Entity, so I could use covariance easy enough, but I want to do some post processing on the query in it's derived state before returning it.

It seems to me that EF must be doing this itself internally, but I'd like to be able to run my query so that the type of the result is Derived type rather than Entity.

Thanks for helping.

Upvotes: 8

Views: 1906

Answers (2)

polkduran
polkduran

Reputation: 2551

Working on the Expression level, you can build a new expression having the Derived type as parameter:

var entityExpr = (Expression<Func<Entity, bool>>)(e => e.Str == "");
var derivedExpr = Expression.Lambda<Func<Derived, bool>>(entityExpr.Body, entityExpr.Parameters);

Upvotes: 5

Wouter de Kort
Wouter de Kort

Reputation: 39898

If you have your expression Expression<Func<Entity, bool>> you can add a Cast<Derived> to it to filter down to all entities that are of that specific type.

Upvotes: 3

Related Questions