如何映射公共財產Source.Name
到私有財產Destination.Name
使用Automapper。如何使用AutoMapper將某些財產映射到私有財產
public class Source
{
public string Name { get; set; }
}
public class Destination
{
private string Name { get; set; }
}
如何映射公共財產Source.Name
到私有財產Destination.Name
使用Automapper。如何使用AutoMapper將某些財產映射到私有財產
public class Source
{
public string Name { get; set; }
}
public class Destination
{
private string Name { get; set; }
}
嘗試使用此一:
Mapper.Initialize(cfg =>
{
cfg.ShouldMapProperty = pi => pi.PropertyType.IsPublic || pi.PropertyType.IsNotPublic;
});
不幸的是,它不能按預期工作。 – MaciejLisCK
該解決方案創建假的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;
}
[私人設置器AutoMapper映射屬性]的可能的複製(http://stackoverflow.com/questions/8355024/automapper-mapping-properties-with-private-setters) –
它不是重複的,因爲整個財產不僅是私人的,而且是私人的。使用私人setter映射屬性很好,但如果整個屬性是私有的,我會收到一個異常。 – MaciejLisCK
您是否閱讀過*全部*答案? –