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

Asp.Net 5 Core项目中如何正确配置AutoMapper解决映射报错问题

问题根因

AutoMapper 中 CreateMap<TSource, TDestination> 的参数顺序为源类型→目标类型,你当前配置的是 User 转 UserViewModel 的映射规则,但业务代码中调用的是 UserViewModel 转 User,自然会触发缺少映射配置的报错。

解决方案

方法1:直接修正现有配置

修改Startup中的映射配置行,添加反向映射即可:

Type[] types = all scannable types...

services.AddAutoMapper((serviceProvider, MapperExpression) =>
{
    // 这行非必需,可以直接删除
    // MapperExpression.ConstructServicesUsing(t => serviceProvider);

    // 调用ReverseMap() 同时生成双向映射规则
    MapperExpression.CreateMap<User, UserViewModel>().ReverseMap();

}, types);

ReverseMap() 会自动生成 UserViewModel → User 的映射规则,不需要重复写两次配置。

方法2:更规范的Profile管理方案(推荐)

如果后续映射规则较多,推荐用Profile类统一管理所有映射,避免Startup配置臃肿:

  1. 新建映射配置类,继承AutoMapper的Profile:
public class MappingProfile : Profile
{
    public MappingProfile()
    {
        // 在此处添加所有映射规则
        CreateMap<User, UserViewModel>().ReverseMap();
    }
}
  1. 修改Startup中的AutoMapper注册代码,自动扫描Profile:
// 直接传入Profile所在的类即可,AutoMapper会自动扫描当前程序集所有Profile
services.AddAutoMapper(typeof(MappingProfile));
补充说明

你的User类继承自IdentityUser<int>,自带的Email、UserName等属性和UserViewModel中的属性名完全一致,AutoMapper默认按属性名匹配映射,不需要额外配置字段映射规则,修正配置后即可正常使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 02:27:01