如何在AutoMapper的ProductProfile中复用CategoryProfile映射逻辑?
解决AutoMapper复用Profile映射的问题
你的问题核心是AutoMapper未加载CategoryProfile中的映射规则,导致映射ProductEntity与ProductDTO时,无法找到CategoryEntity和CategoryDTO的转换逻辑,最终Category字段为空。要复用已有的Profile,只需确保AutoMapper在注册时扫描所有包含Profile的程序集即可。
步骤1:正确注册AutoMapper服务
在.NET Core 6的Program.cs中,替换原来的AutoMapper注册代码,让它自动扫描当前应用所有程序集里的Profile:
// 确保所有Profile被加载 builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
如果你的Profile都集中在某个特定程序集,也可以指定具体程序集,比如:
// 假设Profile都在当前项目程序集里 builder.Services.AddAutoMapper(typeof(Program).Assembly);
步骤2:验证映射逻辑
完成注册后,ProductProfile中的映射会自动复用CategoryProfile里定义的CategoryEntity↔CategoryDTO转换规则,不需要在ProductProfile中重复编写映射代码。
测试示例:
// 注入IMapper var mapper = app.Services.GetRequiredService<IMapper>(); // 构造测试实体 var productEntity = new ProductEntity { Name = "笔记本电脑", Category = new CategoryEntity { Name = "电子产品" } }; // 转换为DTO var productDto = mapper.Map<ProductDTO>(productEntity); // 此时productDto.Category.Name应为"电子产品",不会为空 // 反向转换也同样有效 var convertedBackEntity = mapper.Map<ProductEntity>(productDto);
为什么之前重复写映射能生效?
当你在ProductProfile中重复添加CreateMap<CategoryEntity, CategoryDTO>().ReverseMap();时,AutoMapper会在该Profile中加载这个映射规则,所以转换时能找到对应的逻辑。但复用已有的Profile才是更符合规范的写法,避免代码冗余。
内容的提问来源于stack exchange,提问作者Leandro
相关产品推荐
相关产品推荐

