我有以下课程:
public Company
{
public Person Person {get; set;}
}
public Person
{ }
public Manager : Person
{ }
public Salesperson : Person
{ }
public CompanyDto
{
public Manager Manager {get; set;}
public Salesperon Salesperon {get; set;}
}
如果Person
类型为Manager
,如何更改以下映射,以便Person
映射到Manager
?
cfg.CreateMap<Company, CompanyDto>()
.ForMember(dto => dto.Manager, option => option.MapFrom(model => model.Person))
.ForMember(dto => dto.Salesperon, option => option.MapFrom(model => model.Person))
.ReverseMap();
答案 0 :(得分:2)
添加以下映射:
cfg.CreateMap<Person, Manager>().ReverseMap();
cfg.CreateMap<Person, Salesperson>().ReverseMap();
你需要在创建这样的映射时放置条件:
cfg.CreateMap<Company, CompanyDto>()
.ForMember(dto => dto.Manager, option => option.MapFrom(model => model.Person is Manager ? model.Person : null))
.ForMember(dto => dto.Salesperon, option => option.MapFrom(model => model.Person is Salesperson ? model.Person : null));
对于上述映射,ReverseMap
将无效。您需要明确地设置反向映射,如下所示:
cfg.CreateMap<CompanyDto, Company>()
.ForMember(dto => dto.Person, option => option.MapFrom(model => model.Manager != null ? (Person)model.Manager : model.Salesperon));
希望这有帮助。