Cast lambda expression to derived type
Asked Answered
F

2

8

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.

Foredeck answered 5/4, 2013 at 8:43 Comment(3)
What if you add a Cast<Derived> to your query?Hub
I 'm not sure if this is a duplicate, but it is definitely very similar to this question of mine.Freese
Argh damn. I was being thick. Thanks for pointing out the bleeding obvious.Foredeck
H
3

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.

Hub answered 5/4, 2013 at 8:58 Comment(0)
T
5

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);
Tonietonight answered 5/2, 2016 at 18:4 Comment(1)
I'm using this now for linq2db so I can place my attributes in a derived class. This is the best solution I've found.Deflate
H
3

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.

Hub answered 5/4, 2013 at 8:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.