1 回答

TA貢獻(xiàn)1878條經(jīng)驗(yàn) 獲得超4個(gè)贊
原來(lái)是AutoMapper映射問(wèn)題。
首先,與以下相比,EmployeeEarningDTO內(nèi)部創(chuàng)建了額外的級(jí)別:LastPayCertificateViewModelFlatEmployee
LastPayCertificateViewModel.PayPayAndAllowances.PayAndAllowances
對(duì)比
FlatEmployee.PayAndAllowances
AutoMapper 默認(rèn)映射具有相同名稱(chēng)的屬性。所以在FlatEmployeemap內(nèi)部LastPayCertificateViewModel它會(huì)嘗試映射Dictionary<string, long> PayAndAllowances到EmployeeEarningDTO PayAndAllowances. 但是沒(méi)有從Dictionary<string, long>到的映射EmployeeEarningDTO。相反,有一個(gè)從FlatEmployee到的映射EmployeeEarningDTO,所以你必須告訴 AM 使用它:
configuration.CreateMap<FlatEmployee, LastPayCertificateViewModel>()
.ForMember(dto => dto.EmployeeCode, opt => opt.MapFrom(entity => entity.EmployeeId))
.ForMember(dto => dto.PayAndAllowances, opt => opt.MapFrom(entity => entity)); // <--
其次,映射 from FlatEmployeeto EmployeeEarningDTO- AM 會(huì)自動(dòng)嘗試映射PayAndAllowances屬性,但是沒(méi)有映射 from KeyValuePair<string, long>to BaseEmployeeDictionary。你可以定義這樣的映射
configuration.CreateMap<KeyValuePair<string, long>, BaseEmployeeDictionary>()
.ForMember(dst => dst.Name, opt => opt.MapFrom(src => src.Key))
.ForMember(dst => dst.Amount, opt => opt.MapFrom(src => src.Value));
這將使您可以簡(jiǎn)單地使用
configuration.CreateMap<FlatEmployee, EmployeeEarningDTO>();
但是您可能不會(huì)這樣做,因?yàn)槟幌M總€(gè)都 KeyValuePair<string, long>映射到BaseEmployeeDictionary,因此您可以就地進(jìn)行映射:
configuration.CreateMap<FlatEmployee, EmployeeEarningDTO>()
.ForMember(dto => dto.PayAndAllowances, opt => opt.MapFrom(entity => entity.PayAndAllowances
.Select(src => new BaseEmployeeDictionary { Name = src.Key, Amount = src.Value })));
- 1 回答
- 0 關(guān)注
- 173 瀏覽
添加回答
舉報(bào)