1 回答
TA贡献1878条经验 获得超4个赞
原来是AutoMapper映射问题。
首先,与以下相比,EmployeeEarningDTO内部创建了额外的级别:LastPayCertificateViewModelFlatEmployee
LastPayCertificateViewModel.PayPayAndAllowances.PayAndAllowances
对比
FlatEmployee.PayAndAllowances
AutoMapper 默认映射具有相同名称的属性。所以在FlatEmployeemap内部LastPayCertificateViewModel它会尝试映射Dictionary<string, long> PayAndAllowances到EmployeeEarningDTO PayAndAllowances. 但是没有从Dictionary<string, long>到的映射EmployeeEarningDTO。相反,有一个从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 会自动尝试映射PayAndAllowances属性,但是没有映射 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));
这将使您可以简单地使用
configuration.CreateMap<FlatEmployee, EmployeeEarningDTO>();
但是您可能不会这样做,因为您不希望每个都 KeyValuePair<string, long>映射到BaseEmployeeDictionary,因此您可以就地进行映射:
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 关注
- 139 浏览
添加回答
举报