Express lambda expression for derived type

I need a little piece of magic. I believe that what I am trying to do makes sense, but if I did not see a problem with the plan, the reasons why this would be very welcome.

I have an expression

Expression<Func<Entity, bool>>

and I want to make / convert or even create a completely new expression:

Expression<Func<Derived, bool>>

This is used as an EF filter request, passed as an argument to the repository method. The repository returns an enumerable Entity, so I could use covariance quite easily, but I want to do some post-processing of the request in the received state before returning it.

It seems to me that EF should do this on its own, but I would like to be able to run my query so that the result type is derived, not Entity.

Thanks for the help.

+7
source share
2 answers

If you have an Expression<Func<Entity, bool>> expression, you can add Cast<Derived> to it to filter out all objects related to this particular type.

+3
source

Working with the Expression level, you can create a new expression of type Derived as a parameter:

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

All Articles