我有以下课程
class Employment{
public string Company{get; set;}
public string Since{get; set;}
public string Position{get; set;}
}
class Person{
public string FullName {get; set;}
public Employment Employment{get; set;}
}
我希望将其转换为以下类
class PersonEntity{
public string FullName {get; set;}
public string EmploymentCompany{get; set;}
public string EmploymentSince{get; set;}
public string EmploymentPosition{get; set;}
}
我已定义了以下映射
mce.CreateMap<Person, PersonEntity>();
mce.CreateMap<Employment, PersonEntity>
.ForMember(d=>d.EmploymentCompany, o=>o.MapFrom(s=>s.Company))
.ForMember(d=>d.EmploymentSince, o=>o.MapFrom(s=>s.Since))
.ForMember(d=>d.EmploymentPosition, o=>o.MapFrom(s=>s.Position))
.ForAllOtherMembers(o=>o.Ignore())
;
当我运行时,它给我的第一个错误是d.EmploymentCompany未映射。如果我添加了Ignore(),则它在JobSince上会给出错误,因为未映射。
正确的映射方式是什么?
答案 0 :(得分:0)
正确的映射类的方法如下:
CreateMap<Person, PersonEntity>()
.ForMember(d => d.EmploymentCompany, o => o.MapFrom(s => s.Employment.Company))
.ForMember(d => d.EmploymentSince, o => o.MapFrom(s => s.Employment.Since))
.ForMember(d => d.EmploymentPosition, o => o.MapFrom(s => s.Employment.Position)) ;