.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加载生效。
解决办法
- 优先修复异步调用逻辑,给
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); }
- 若修复后依旧报错,调整AutoMapper的程序集扫描规则,显式把
CountyProfile所在的程序集加入扫描范围:
public static void AddInfrastructureMappings(this IServiceCollection services) { // 传入CountyProfile所在程序集,确保映射配置被扫描到 services.AddAutoMapper(Assembly.GetExecutingAssembly(), typeof(CountyProfile).Assembly); }
内容的提问来源于stack exchange,提问作者Alex Ivan
相关产品推荐
相关产品推荐

