AutoMapper 是 C# 中简化对象映射的常用库,它能自动将一个对象的属性值复制到另一个结构相似的对象中,避免手写大量赋值代码。核心在于配置映射规则,之后只需一行代码完成转换。
安装与基础配置
通过 NuGet 安装 AutoMapper 包(如 AutoMapper 和 AutoMapper.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<UserEntity, UserDto>();
CreateMap<UserDto, UserEntity>()
.ForMember(dest => dest.CreatedAt, opt => opt.Ignore());
}
}
CreateMap<tsource tdestination>()</tsource>声明双向映射基础
ForMember可定制特定属性行为,比如忽略、条件映射、值转换 同名同类型属性默认自动映射,无需额外配置
执行映射:注入 IMapper 并调用 Map
在需要转换的地方注入 IMapper 接口(如 Controller 或 Service 中):
var dto = _mapper.Map<userdto>(entity);</userdto>—— 对象转 DTO
var entity = _mapper.Map<userentity>(dto);</userentity>—— DTO 转实体 也可映射集合:
_mapper.Map<list>>(userList)</list>
常见注意事项
映射不是万能的,需留意以下细节:
属性名必须匹配(默认忽略大小写),或用ForMember显式指定源字段 嵌套对象会自动递归映射,前提是已为嵌套类型配置了对应规则 值类型不为 null 时注意目标类型是否可空,必要时用
ConvertUsing处理 调试映射问题可用
AssertConfigurationIsValid()验证配置合法性
基本上就这些。合理配置 Profile + 注入 IMapper,就能让对象转换变得干净又可靠。
