If I have two nearly identical classes Animal and AnimalViewModel and an expression tree related to the viewmodel, how can I translate it to Animal?
public class Animal
{
public string Species { get; set; }
public string Name { get; set; }
public string Sound { get; set; }
}
public class AnimalViewModel : ViewModelBase
{
public string Species { get; set; }
public string Name { get; set; }
public string Sound { get; set; }
}
How can I translate an Expression<Func<AnimalViewModel,bool>> to Expression<Func<Animal,bool>>?
public static Expression<Func<Animal,bool>> Translate (Expression<Func<AnimalViewModel,bool>> expression)
{
// What goes here? I assume I have to traverse the tree somehow.
}
Here’s a visitor that does the job.
.Bodyof the tree, substituting the parameter, and switching any member-access against the old type to a like-named member on the new typeCode:
Note that if you have
x.Something.Nameyou might need to be a bit more careful, but this should get you a reasonable way.