我是automapper的新手。我有一个具有对象集合的类。我需要该类映射到另一个具有不同名称的对象。我需要将员工映射到employeeDto。这两个类都有不同的名称和不同的名称。如果它们具有不同的名称,是否可以使用automapper进行映射?
public class Employee
{
public string Name { get; set; }
public string Address { get; set; }
public List<Job> Jobs { get; set; }
}
public class Job
{
public string CompanyName { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
public class EmployeeDto
{
public string Fullname { get; set; }
public string Location { get; set; }
public List<WorkExperience> WorkExperience { get; set; }
}
public class WorkExperience
{
public string NameOfCompany { get; set; }
public DateTime DateBegin { get; set; }
public DateTime DateEnd { get; set; }
}
答案 0 :(得分:4)
您可以配置映射以手动处理Jobs
列表到WorkExperience
列表。请参阅AutoMapper文档中的Projection section
AutoMapper.Mapper.Initialize(cfg =>
{
cfg.CreateMap<Employee, EmployeeDto>()
.ForMember(dest => dest.Fullname, opt => opt.MapFrom(src => src.Name))
.ForMember(dest => dest.Location, opt => opt.MapFrom(src => src.Address))
.ForMember(dest => dest.WorkExperience, opt => opt.MapFrom(src => src.Jobs));
cfg.CreateMap<Job, WorkExperience>()
.ForMember(dest => dest.NameOfCompany, opt => opt.MapFrom(src => src.CompanyName))
.ForMember(dest => dest.DateBegin, opt => opt.MapFrom(src => src.StartDate))
.ForMember(dest => dest.DateEnd, opt => opt.MapFrom(src => src.EndDate));
});
此外,如果您想要反向转换,可以添加ReverseMap()以避免代码重复。