AutoMapper映射问题:Quotation关联Customer未映射至ViewModel字段
解决AutoMapper映射嵌套Customer属性到ViewModel的问题
你已经正确通过Include加载了Quotation关联的Customer数据,但AutoMapper默认不会自动把嵌套对象的属性映射到ViewModel的平级字段——因为QuotationDetailsViewModel.Name对应的是Quotation.Customer.Name,不是直接的同名属性匹配。我来帮你修正配置:
问题根源
你当前的MappingProfile只做了简单的双向映射声明,但没有明确告诉AutoMapper如何从嵌套的Customer对象中取Name值。AutoMapper默认只会映射同名的直接属性,不会自动遍历嵌套对象匹配字段。
修正后的MappingProfile配置
更新你的MappingProfile.cs,显式指定成员映射规则:
public class MappingProfile : Profile { public MappingProfile() { // 核心配置:Quotation 转 QuotationDetailsViewModel CreateMap<Quotation, QuotationDetailsViewModel>() .ForMember(dest => dest.QuotationId, opt => opt.MapFrom(src => src.Id)) // 映射报价ID .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Customer.Name)) // 从嵌套Customer取名称 // 以下两个属性是同名匹配,AutoMapper会自动处理,显式声明可提升可读性 .ForMember(dest => dest.CustomerId, opt => opt.MapFrom(src => src.CustomerId)) .ForMember(dest => dest.Status, opt => opt.MapFrom(src => src.Status)) .ReverseMap(); // 如果需要反向映射(ViewModel转Quotation),保留这一行 // 你之前配置的QuotationDetailsViewModel到Customer的映射是多余的,当前场景用不到,可以删除 // CreateMap<QuotationDetailsViewModel, Customer>().ReverseMap(); } }
额外优化建议
- 避免空引用异常:如果
Quotation.Customer可能为null,建议用空条件运算符做防护:.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Customer?.Name)) - 确认AutoMapper注册正确:在
Startup.cs的ConfigureServices中,确保已经添加了AutoMapper服务:services.AddAutoMapper(typeof(MappingProfile));
测试验证
现在运行你原来的代码:
var quotation = context.Quotation.Include("Customer").Single(q => q.Id == 1); var quotationDetailsViewModel = mapper.Map<QuotationDetailsViewModel>(quotation);
quotationDetailsViewModel.Name应该能正确填充quotation.Customer.Name的值了。
内容的提问来源于stack exchange,提问作者prinkpan
相关产品推荐
相关产品推荐

