I\'m struggling with the modification of an expression tree. I\'ve simplified the example to make it easier to display here. Let\'s start with two classes:
p
After some more searching I found the answer here: How to change a type in an expression tree?. It didn't show up in the suggestions when I submitted my question.
As I don't really need the Filter class, I instead created an interface with only the properties that I want to be able to filter (IEntity) and modified the Entity class to implement it. Now I'm able to get the desired results with this:
// Example use: return entities.Entities.Where(ExpressionTransformer<IEntity,Entity>.Transform(filter));
internal static class ExpressionTransformer<TFrom, TTo> where TTo : TFrom
{
public class Visitor : ExpressionVisitor
{
private ParameterExpression _parameter;
public Visitor(ParameterExpression parameter)
{
_parameter = parameter;
}
protected override Expression VisitParameter(ParameterExpression node)
{
return _parameter;
}
}
public static Expression<Func<TTo, bool>> Tranform(Expression<Func<TFrom, bool>> expression)
{
ParameterExpression parameter = Expression.Parameter(typeof(TTo));
Expression body = new Visitor(parameter).Visit(expression.Body);
return Expression.Lambda<Func<TTo, bool>>(body, parameter);
}
}
In case you need to do something similar but you cannot work with an interface or you cannot make your class implement that interface: the answer is also in the above mentioned answer