如何使用AutoMapper映射一些属性到私有属性

本文关键字:属性 何使用 AutoMapper 映射 | 更新日期: 2023-09-27 18:19:14

如何使用Automapper将公共属性Source.Name映射到私有属性 Destination.Name

public class Source
{
    public string Name { get; set; }
}

public class Destination
{
    private string Name { get; set; }
}

如何使用AutoMapper映射一些属性到私有属性

试着用这个:

Mapper.Initialize(cfg =>
          {
            cfg.ShouldMapProperty = pi => pi.PropertyType.IsPublic || pi.PropertyType.IsNotPublic;
        });

此解决方案创建假lambda表达式。在这个例子中,它创建了(Destination) => Destination.Name lambda。

Mapper.CreateMap<Source, Destination>()
    .ForMember(CreateMemberLambda<Destination>("Name"), mo => mo.MapFrom(sm => sm.Name));
var source = new Source() { Name = "foo" };
var destination = Mapper.Map<Destination>(source);

public Expression<Func<T, object>> CreateMemberLambda<T>(string parameterName)
{
    var type = typeof(T);
    var bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
    var parameter = type.GetProperty(parameterName, bindFlags);
    var classExpression = Expression.Parameter(type, type.Name);
    var memberAccessExpression = Expression.MakeMemberAccess(classExpression, parameter);
    var lambda = Expression.Lambda<Func<T, object>>(memberAccessExpression, classExpression);
    return lambda;
}

我知道这篇文章很老了,但我发现了同样的问题,并修改了maciejlisk暴露的CreateMemberLambda方法,

public Expression<Func<T, object>> CreateMemberLambda<T>(string parameterName)
    {
        var type = typeof(T);
        var bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField;
        var parameter = type.GetField(parameterName, bindFlags);
        var classExpression = Expression.Parameter(type, type.Name);
        var memberAccessExpression = Expression.MakeMemberAccess(classExpression, parameter);
        var lambda = Expression.Lambda<Func<T, object>>(memberAccessExpression, classExpression);
        return lambda;
    }