我知道自动映射器可以自动映射自:
class SomeClassA
{
public int Id { get; set; }
public B Member { get; set; }
}
class SomeClassB
{
public int Id { get; set; }
public string Name { get; set; }
}
自:
class SomeClassADto
{
public int Id { get; set; }
public int Member_Id { get; set; }
public string Member_Name { get; set; }
}
但是,如何使自动映射器自动从我的SomeClassADto映射到SomeClassA呢?
不是世界上最漂亮的东西,但它确实有效。缺点是维护很痛苦,因为您将属性添加到 DTO 和类需要更新映射。
var config = new MapperConfiguration(x =>
{
x.CreateMap<SomeClassADto, SomeClassB>()
.ForMember(i => i.Id, i => i.MapFrom(src => src.Member_Id))
.ForMember(i => i.Name, i => i.MapFrom(src => src.Member_Name));
x.CreateMap<SomeClassADto, SomeClassA>()
.AfterMap((s, d, r) => d.Member = r.Mapper.Map<SomeClassB>(s));
});
IMapper mapper = config.CreateMapper();
var foo = mapper.Map<SomeClassA>(new SomeClassADto() { Id = 1, Member_Id = 2, Member_Name = "Name" });