neSHa
✅ AutoMapper and Expression
if you are intrested in solution:
public class ExpressionManipulator
{
public Expression<Func<T, bool>> ConvertToTExpression(Expression<Func<TDto, bool>> sourceExpression)
{
var parameter = Expression.Parameter(typeof(T), sourceExpression.Parameters[0].Name);
var body = new TExpressionVisitor(parameter).Visit(sourceExpression.Body);
var TExpression= Expression.Lambda<Func<T, bool>>(body, parameter);
return TExpression;
}
private class TExpressionVisitor : ExpressionVisitor
{
private readonly ParameterExpression _parameterExpression;
public TExpressionVisitor(ParameterExpression parameterExpression)
{
_parameterExpression = parameterExpression;
}
protected override Expression VisitParameter(ParameterExpression node)
{
return _parameterExpression;
}
protected override Expression VisitMember(MemberExpression node)
{
if (node.Member.DeclaringType == typeof(TDto))
{
var memberName = node.Member.Name;
var targetMember = typeof(T).GetProperty(memberName);
if (targetMember != null)
{
return Expression.MakeMemberAccess(_parameterExpression, targetMember);
}
}
return base.VisitMember(node);
}
}
}
67 replies