I have a method like this:
private bool Method_1(Expression<Func<IPerson, bool>> expression)
{
/* Some code that will call Method_2 */
}
In this method I want to change the IPerson
type to another type. I want to call another method that looks like this:
private bool Method_2(Expression<Func<PersonData, bool>> expression)
{
/* Some code */
}
So, in method_1
I need to change IPerson
to PersonData
. How can I do this?
Edit:
When I call: Method_1(p => p.Id == 1)
I want to 'save' the condition (p.Id == 1
) but I want to execute this condition on another type, namely IPerson
. So, I need to alter the expression or create a new expression with IPerson
EDIT II:
For those who are interested, this is (for now) my solution:
private class CustomExpressionVisitor<T> : ExpressionVisitor
{
ParameterExpression _parameter;
public CustomExpressionVisitor(ParameterExpression parameter)
{
_parameter = parameter;
}
protected override Expression VisitParameter(ParameterExpression node)
{
return _parameter;
}
protected override Expression VisitMember(MemberExpression node)
{
if (node.Member.MemberType == System.Reflection.MemberTypes.Property)
{
MemberExpression memberExpression = null;
var memberName = node.Member.Name;
var otherMember = typeof(T).GetProperty(memberName);
memberExpression = Expression.Property(Visit(node.Expression), otherMember);
return memberExpression;
}
else
{
return base.VisitMember(node);
}
}
}
And this is the way I use it:
public virtual bool Exists(Expression<Func<Dto, bool>> expression)
{
var param = Expression.Parameter(typeof(I));
var result = new CustomExpressionVisitor<I>(param).Visit(expression.Body);
Expression<Func<I, bool>> lambda = Expression.Lambda<Func<I, bool>>(result, param);
bool exists = _repository.Exists(lambda);
return exists;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…