Web Api项目中Automapper与NPoco映射配置缺失异常问题排查
排查AutoMapper映射异常:"Missing type map configuration or unsupported mapping"
让我来帮你分析这个问题,看了你的代码后,发现两个核心问题导致了这个异常:
1. Profile配置错误:误用静态Mapper.CreateMap
你的AutoMapperProfile类里,在Configure方法中调用了静态的Mapper.CreateMap,而不是Profile基类提供的CreateMap方法。这会导致你的映射配置没有被添加到Profile中,当你把Profile注册到AutoMapper时,这些映射规则根本没被加载。
修正后的Profile代码:
public class AutoMapperProfile : Profile { protected override void Configure() { // 使用Profile基类的CreateMap方法,而非静态Mapper.CreateMap CreateMap<FormulaComponent, FormulaComponentDto>().ReverseMap(); CreateMap<Component, ComponentDto>().ReverseMap(); } }
ReverseMap()会自动创建反向的映射规则(比如FormulaComponentDto到FormulaComponent),所以不需要单独再写一遍反向的CreateMap。
2. AutoMapper初始化方式不正确
你直接调用Mapper.AddProfile<AutoMapperProfile>(),但在旧版本的AutoMapper中,正确的做法是通过Mapper.Initialize来加载Profile,否则Profile的配置不会被正确注册到映射引擎里。
修正后的LightInject初始化代码:
public partial class Startup { public static void InitLightInject(HttpConfiguration config) { var container = new ServiceContainer(); // 用Initialize方法初始化AutoMapper并加载Profile Mapper.Initialize(cfg => { cfg.AddProfile<AutoMapperProfile>(); }); container.Register<IMappingEngine>(c => Mapper.Engine); // 别忘了其他必要的容器注册逻辑 } }
可选优化:简化映射调用代码
你当前的映射调用指定了集合的泛型参数,其实AutoMapper可以自动推断源类型,简化写法:
public IEnumerable<FormulaComponent> GetAll() { var formulaComponents = _repository.Get().Include(x => x.Component).ToList(); // 无需指定源集合类型,AutoMapper会自动处理 return _mapper.Map<IEnumerable<FormulaComponent>>(formulaComponents); }
这样修改后,嵌套的Component属性也会被正确映射,因为我们已经配置了Component和ComponentDto的双向映射规则,AutoMapper会自动递归处理嵌套对象。
内容的提问来源于stack exchange,提问作者Mikhail Kostiuchenko
相关产品推荐
相关产品推荐

