Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 796
MJM Avatar asked Apr 05 '13 08:04

MJM


1 Answers

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);
like image 94
polkduran Avatar answered Sep 19 '22 12:09

polkduran