新增心愿单商品触发AutoMapperMappingException映射错误问题求助
问题根因分析
- 核心错误1:缺少
ProductDetails实体到ProductDetailsDtoWithPrimaryImageDTO的映射配置,插入完成后回写DTO时需要转换该属性,触发映射异常 - 核心错误2:
WishlistItem实体的外键字段名为ProductDetailsId,WishlistItemDto对应字段为ProductDetailId,双向映射时仅配置了正向规则,反向映射时属性名不匹配导致映射失败 - 数据能成功入库的原因:插入流程中你手动查询赋值了
ProductDetails实体,没有触发嵌套DTO转换,因此入库逻辑正常,异常出现在入库完成后将实体映射回DTO返回的步骤
修复方案
步骤1:修正WishlistItem相关映射配置
修改你的WishlistItemProfile类如下:
public WishlistItemProfile() { // 原有基础映射保留 CreateMap<WishlistItem, WishListItemCreationDto>().ReverseMap(); CreateMap<WishlistItemDto, WishListItemCreationDto>().ReverseMap(); // 修正WishlistItem与WishlistItemDto的双向映射 CreateMap<WishlistItem, WishlistItemDto>() // 正向映射:实体外键字段映射到DTO字段 .ForMember(dto => dto.ProductDetailId, opt => opt.MapFrom(entity => entity.ProductDetailsId)) .ForMember(dto => dto.ProductDetails, opt => opt.MapFrom(entity => entity.ProductDetails)) .ReverseMap() // 反向映射:DTO字段映射到实体外键字段 .ForMember(entity => entity.ProductDetailsId, opt => opt.MapFrom(dto => dto.ProductDetailId)) // 可选:反向映射时忽略ProductDetails属性,避免覆盖业务层手动查询的实体 .ForMember(entity => entity.ProductDetails, opt => opt.Ignore()); // 新增商品详情实体与DTO的映射 CreateMap<ProductDetails, ProductDetailsDtoWithPrimaryImage>() // Sku为计算属性,两边计算规则一致无需映射,可显式忽略 .ForMember(dto => dto.Sku, opt => opt.Ignore()) .ReverseMap(); }
步骤2:补充依赖类型的映射配置
确认你已经添加了以下两个依赖类型的映射,没有的话补充到对应的Profile中:
// 商品基础实体与显示DTO的映射 CreateMap<Product, ProductDisplayEntity>().ReverseMap(); // 商品属性实体与DTO的映射 CreateMap<ProductAttributeValue, ProductAttributeWithValueDto>().ReverseMap();
内容的提问来源于stack exchange,提问作者dotnetlooper
相关产品推荐
相关产品推荐

