You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Web API使用Automapper映射County时报缺失类型映射配置错误怎么解决

错误原因
  • 核心原因是你调用_context.Counties.ToListAsync()异步方法时未添加await关键字,此时counties变量的实际类型是Task<List<County>>而非你预期的List<County>。你仅配置了County与CountyResponse的类型映射规则,AutoMapper找不到Task<List<County>>到List<CountyResponse>>的映射配置,因此抛出该异常。
  • 次要可能原因:若CountyProfile类与AddInfrastructureMappings扩展方法不在同一个程序集,Assembly.GetExecutingAssembly()只会扫描扩展方法所在程序集的配置,导致CountyProfile未被AutoMapper加载生效。
解决办法
  1. 优先修复异步调用逻辑,给ToListAsync()添加await关键字,拿到实际的County实体集合后再做映射,修改后的服务代码如下:
public async Task<Result<List<CountyResponse>>> GetAllAsync()
{
    // 加await等待异步查询完成,获取List<County>类型的结果
    var counties = await _context.Counties.ToListAsync();
    var mappedCounties = _mapper.Map<List<CountyResponse>>(counties);
    return await Result<List<CountyResponse>>.SuccessAsync(mappedCounties);
}
  1. 若修复后依旧报错,调整AutoMapper的程序集扫描规则,显式把CountyProfile所在的程序集加入扫描范围:
public static void AddInfrastructureMappings(this IServiceCollection services)
{
    // 传入CountyProfile所在程序集,确保映射配置被扫描到
    services.AddAutoMapper(Assembly.GetExecutingAssembly(), typeof(CountyProfile).Assembly);
}

内容的提问来源于stack exchange,提问作者Alex Ivan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 20:09:04