C# 如何使用AutoMapper - 简化对象之间的映射

AutoMapper 是 C# 中简化对象映射的常用库,通过配置 Profile 类定义 CreateMap 规则并注入 IMapper 接口,即可用一行代码完成实体与 DTO 的双向转换,支持忽略、条件映射和集合映射,需注意属性匹配、嵌套映射及空值处理。

AutoMapper 是 C# 中简化对象映射的常用库,它能自动将一个对象的属性值复制到另一个结构相似的对象中,避免手写大量赋值代码。核心在于配置映射规则,之后只需一行代码完成转换。

安装与基础配置

通过 NuGet 安装 AutoMapper 包(如 AutoMapperAutoMapper.Extensions.Microsoft.DependencyInjection,后者用于 ASP.NET Core 依赖注入)。

在启动时注册服务(以 .NET 6+ 为例):

  • Program.cs 中调用 builder.Services.AddAutoMapper(typeof(YourProfileClass))
  • 或使用程序集扫描:AddAutoMapper(Assembly.GetExecutingAssembly())

定义映射关系:使用 Profile 类

推荐用自定义 Profile 类集中管理映射规则,提高可维护性。

例如:

public class UserProfile : Profile
{
    public UserProfile()
    {
        CreateMap();
        CreateMap()
            .ForMember(dest => dest.CreatedAt, opt => opt.Ignore());
    }
}
  • CreateMap() 声明双向映射基础
  • ForMember 可定制特定属性行为,比如忽略、条件映射、值转换
  • 同名同类型属性默认自动映射,无需额外配置

执行映射:注入 IMapper 并调用 Map

在需要转换的地方注入 IMapper 接口(如 Controller 或 Service 中):

  • var dto = _mapper.Map(entity); —— 对象转 DTO
  • var entity = _mapper.Map(dto); —— DTO 转实体
  • 也可映射集合:_mapper.Map>(userList)

常见注意事项

映射不是万能的,需留意以下细节:

  • 属性名必须匹配(默认忽略大小写),或用 ForMember 显式指定源字段
  • 嵌套对象会自动递归映射,前提是已为嵌套类型配置了对应规则
  • 值类型不为 null 时注意目标类型是否可空,必要时用 ConvertUsing 处理
  • 调试映射问题可用 AssertConfigurationIsValid() 验证配置合法性

基本上就这些。合理配置 Profile + 注入 IMapper,就能让对象转换变得干净又可靠。