I have used C# expressions before based on lamdas, but I have no experience composing them by hand. Given an Expression<Func<SomeType, bool>> originalPredicate
, I want to create an Expression<Func<OtherType, bool>> translatedPredicate
.
In this case SomeType and OtherType have the same fields, but they are not related (no inheritance and not based on a common interface).
Background: I have a repository implementation based on LINQ to SQL. I project the LINQ to SQL entities to my Model entities, to keep my model in POCO. I want to pass expressions to the repository (as a form of specifications) but they should be based on the model entities. But I can't pass those expressions to the data context, since it expects expressions based on the LINQ to SQL entities.
There is one other way I have found, that also includes wrapping your original delegate.
With
Expression
, the simplest way is with a conversion expression:Note however that this will be supported differently by different providers. EF might not like it, for example, even if LINQ-to-SQL does.
The other option is to rebuild the expression tree completely, using reflection to find the corresponding members. Much more complex.
I had the same issue as you and i fixed it like this with EF:
Entity Framework knows how to build the correct sql command. Converting the expression is much more complicated, because it is built to be immutable and could cause undesired run time effects if you do something wrong, and, in my case at least, it is not needed.
There is no implicit way to do the translation. You have to wrap your existing delegate inside a lambda that creates a new type from the argument type:
Where
OtherTypeFromSomeType
creates theOtherType
instance from theSomeType
argument.