AutoMapper 如何将源对象的子对象映射到目标对象(针对 ProjectTo 的场景)?
源对象的类定义如下:
public class JobPosition
{
public Enterprise Enterprise { get; set; }
}
public class Enterprise
{
public long Key { get; set; }
public string Name { get; set; }
public DateTime CreateDate { get; set; }
}
目标对象的类定义如下:
public class EnterpriseDto
{
public long Key { get; set; }
public string Name { get; set; }
}
目前采用的一个一个属性手动映射的笨方法:
cfg.CreateMap<JobPosition, EnterpriseDto>()
.ForMember(dto => dto.Key, o => o.MapFrom(p => p.Enterprise.Key))
.ForMember(dto => dto.Name, o => o.MapFrom(p => p.Enterprise.Name));
请问有没有更好的映射配置方法?
var mapper = config.CreateMapper();
// or
var mapper = new Mapper(config);
OrderDto dto = mapper.Map<OrderDto>(order);
// or
OrderDto dto = Mapper.Map<OrderDto>(order);
参考URL:http://docs.automapper.org/en/stable/Getting-started.html#how-do-i-use-automapper