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<UserEntity, UserDto>();
CreateMap<UserDto, UserEntity>()
.ForMember(dest => dest.CreatedAt, opt => opt.Ignore());
}
}CreateMap<tsource tdestination>()</tsource> 声明双向映射基础ForMember 可定制特定属性行为,比如忽略、条件映射、值转换在需要转换的地方注入 IMapper 接口(如 Controller 或 Service 中):
var dto = _mapper.Map<userdto>(entity);</userdto> —— 对象转 DTOvar entity = _mapper.Map<userentity>(dto);</userentity> —— DTO 转实体_mapper.Map<list>>(userList)</list>
映射不是万能的,需留意以下细节:
ForMember 显式指定源字段ConvertUsing 处理AssertConfigurationIsValid() 验证配置合法性基本上就这些。合理配置 Profile + 注入 IMapper,就能让对象转换变得干净又可靠。
以上就是C# 如何使用AutoMapper - 简化对象之间的映射的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号