AutoMapper 是 C# 中简化对象映射的常用库,通过配置 Profile 类定义 CreateMap 规则并注入 IMapper 接口,即可用一行代码完成实体与 DTO 的双向转换,支持忽略、条件映射和集合映射,需注意属性匹配、嵌套映射及空值处理。
AutoMapper 是 C# 中简化对象映射的常用库,它能自动将一个对象的属性值复制到另一个结构相似的对象中,避免手写大量赋值代码。核心在于配置映射规则,之后只需一行代码完成转换。

通过 NuGet 安装 AutoMapper 包(如 AutoMapper 和 AutoMapper.Extensions.Microsoft.DependencyInjection,后者用于 ASP.NET Core 依赖注入)。
在启动时注册服务(以 .NET 6+ 为例):
builder.Services.AddAutoMapper(typeof(YourProfileClass))
AddAutoMapper(Assembly.GetExecutingAssembly())
推荐用自定义 Profile 类集中管理映射规则,提高可维护性。
例如:
public class UserProfile : Profile
{
public UserProfile()
{
CreateMap();
CreateMap()
.ForMember(dest => dest.CreatedAt, opt => opt.Ignore());
}
} CreateMap() 声明双向映射基础ForMember 可定制特定属性行为,比如忽略、条件映射、值转换在需要转换的地方注入 IMapper 接口(如 Controller 或 Service 中):
var dto = _mapper.Map(entity); —— 对象转 DTOvar entity = _mapper.Map(dto); —— DTO 转实体_mapper.Map>(userList)
映射不是万能的,需留意以下细节:
ForMember 显式指定源字段ConvertUsing 处理AssertConfigurationIsValid() 验证配置合法性基本上就这些。合理配置 Profile + 注入 IMapper,就能让对象转换变得干净又可靠。