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:
public class Filter
{
public string FilterableProperty1 { get; set; }
public string FilterableProperty2 { get; set; }
}
public class Entity
{
public string FilterableProperty1 { get; set; }
public string FilterableProperty2 { get; set; }
public string NonFilterableProperty { get; set; }
}
All properties in the Filter class also exist in the Entity class. Now I would like to use the Filter class to return the desired entities with a method like this:
public IEnumerable<Entity> GetEntities(Expression<Func<Filter, bool>> filter)
{
Expression<Func<Entity, bool>> convertedFilter = Expression.Lambda<Func<Entity, bool>>(
filter.Body,
Expression.Parameter(typeof(Entity), filter.Parameters[0].Name));
using (MyEntities entities = new MyEntities())
{
return entities.Entities.Where(convertedFilter);
}
}
So basically I just change the type of the expression parameter. Now when I call the function like this:
public IEnumerable<Entity> GetFilteredEntities()
{
return GetEntities(x => x.FilterableProperty1 == "Test");
}
I get an exception saying that the parameter x was not found in the specified query expression. Obviously by replacing the ParameterExpression I am breaking something. How can I create a new expression with the correct type that takes over (or rebuilds) the body of the original expression ?