C# AutoMapper对象映射详解

news2025/5/25 0:14:34

引言

在现代软件开发中,特别是采用分层架构的应用程序,我们经常需要在不同的对象类型之间进行转换。例如,从数据库实体(Entity)转换为数据传输对象(DTO),或者从视图模型(ViewModel)转换为领域模型(Domain Model)。手动编写这些转换代码不仅繁琐,还容易出错。这就是 AutoMapper 这类对象映射工具的价值所在。

本文将详细介绍 C# 中 AutoMapper 的使用方法、最佳实践以及一些高级特性,帮助你在项目中高效地实现对象映射。

什么是 AutoMapper?

AutoMapper 是一个简单、实用的 .NET 对象映射工具,它可以自动将一个对象的属性值复制到另一个对象中,从而消除了手动编写重复的对象转换代码的需要。

AutoMapper 的核心理念是约定大于配置,它会根据属性名称的匹配自动创建映射关系,同时也提供了丰富的配置选项来处理复杂的映射场景。

安装 AutoMapper

在开始使用 AutoMapper 之前,我们需要先安装它。使用 NuGet 包管理器可以轻松完成这一步:

# 使用 NuGet Package Manager Console
Install-Package AutoMapper

# 或者使用 .NET CLI
dotnet add package AutoMapper

对于 ASP.NET Core 应用程序,你可能还想安装 AutoMapper 的依赖注入扩展:

# 使用 NuGet Package Manager Console
Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection

# 或者使用 .NET CLI
dotnet add package AutoMapper.Extensions.Microsoft.DependencyInjection

基本使用

创建映射配置

使用 AutoMapper 的第一步是创建映射配置。以下是一个简单的例子:

using AutoMapper;

// 源类和目标类
public class Customer
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

public class CustomerDto
{
    public int Id { get; set; }
    public string FullName { get; set; }
    public string Email { get; set; }
}

// 创建映射配置
var config = new MapperConfiguration(cfg => 
{
    cfg.CreateMap<Customer, CustomerDto>()
       .ForMember(dest => dest.FullName, 
                  opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}"));
});

// 创建映射器实例
var mapper = config.CreateMapper();

执行映射

一旦配置好映射关系,就可以使用 mapper.Map<TDestination>(source) 方法执行映射:

// 创建源对象
var customer = new Customer
{
    Id = 1,
    FirstName = "John",
    LastName = "Doe",
    Email = "john.doe@example.com"
};

// 执行映射
var customerDto = mapper.Map<CustomerDto>(customer);

// 输出结果
Console.WriteLine($"Id: {customerDto.Id}");
Console.WriteLine($"FullName: {customerDto.FullName}");
Console.WriteLine($"Email: {customerDto.Email}");

输出结果:

Id: 1
FullName: John Doe
Email: john.doe@example.com

在 ASP.NET Core 中使用 AutoMapper

在 ASP.NET Core 应用程序中,我们可以利用依赖注入来简化 AutoMapper 的使用。

注册 AutoMapper 服务

Program.csStartup.cs 中注册 AutoMapper 服务:

// Program.cs in .NET 6+
var builder = WebApplication.CreateBuilder(args);

// 添加 AutoMapper 服务
builder.Services.AddAutoMapper(typeof(Program).Assembly);

// 或者指定包含配置文件的程序集
// builder.Services.AddAutoMapper(typeof(MappingProfile).Assembly);

var app = builder.Build();
// ...

创建映射配置文件

为了保持代码的整洁,我们通常会创建单独的映射配置文件:

using AutoMapper;

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        // 配置 Customer 到 CustomerDto 的映射
        CreateMap<Customer, CustomerDto>()
            .ForMember(dest => dest.FullName, 
                      opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}"));
        
        // 可以在这里添加更多映射配置
    }
}

在控制器中使用 AutoMapper

通过依赖注入在控制器中使用 AutoMapper:

[ApiController]
[Route("api/[controller]")]
public class CustomersController : ControllerBase
{
    private readonly IMapper _mapper;
    private readonly ICustomerRepository _repository;

    public CustomersController(IMapper mapper, ICustomerRepository repository)
    {
        _mapper = mapper;
        _repository = repository;
    }

    [HttpGet("{id}")]
    public ActionResult<CustomerDto> GetCustomer(int id)
    {
        var customer = _repository.GetById(id);
        
        if (customer == null)
            return NotFound();
            
        return _mapper.Map<CustomerDto>(customer);
    }
    
    [HttpGet]
    public ActionResult<IEnumerable<CustomerDto>> GetAllCustomers()
    {
        var customers = _repository.GetAll();
        return Ok(_mapper.Map<IEnumerable<CustomerDto>>(customers));
    }
}

高级映射技巧

处理不同名称的属性

当源对象和目标对象的属性名称不同时,可以使用 ForMember 方法来指定映射关系:

CreateMap<Source, Destination>()
    .ForMember(dest => dest.DestinationProperty, 
               opt => opt.MapFrom(src => src.SourceProperty));

条件映射

有时我们只想在特定条件下执行映射:

CreateMap<Source, Destination>()
    .ForMember(dest => dest.Property, 
               opt => opt.Condition(src => src.SomeValue != null));

值转换器

对于需要进行复杂转换的情况,可以使用值转换器:

CreateMap<Source, Destination>()
    .ForMember(dest => dest.FormattedDate, 
               opt => opt.MapFrom(src => src.Date.ToString("yyyy-MM-dd")));

集合映射

AutoMapper 可以自动处理集合之间的映射:

// 源类和目标类
public class Order
{
    public int Id { get; set; }
    public List<OrderItem> Items { get; set; }
}

public class OrderDto
{
    public int Id { get; set; }
    public List<OrderItemDto> Items { get; set; }
}

// 映射配置
CreateMap<Order, OrderDto>();
CreateMap<OrderItem, OrderItemDto>();

// 使用
var orderDto = _mapper.Map<OrderDto>(order);

扁平化映射

当目标对象的属性需要从源对象的嵌套属性中获取值时,可以使用扁平化映射:

// 源类和目标类
public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Address Address { get; set; }
}

public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string ZipCode { get; set; }
}

public class CustomerViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Street { get; set; }
    public string City { get; set; }
    public string ZipCode { get; set; }
}

// 映射配置
CreateMap<Customer, CustomerViewModel>()
    .ForMember(dest => dest.Street, opt => opt.MapFrom(src => src.Address.Street))
    .ForMember(dest => dest.City, opt => opt.MapFrom(src => src.Address.City))
    .ForMember(dest => dest.ZipCode, opt => opt.MapFrom(src => src.Address.ZipCode));

或者使用更简洁的方式:

CreateMap<Customer, CustomerViewModel>()
    .ForMember(dest => dest.Street, opt => opt.MapFrom(src => src.Address.Street))
    .ForMember(dest => dest.City, opt => opt.MapFrom(src => src.Address.City))
    .ForMember(dest => dest.ZipCode, opt => opt.MapFrom(src => src.Address.ZipCode));

自定义值解析器

对于更复杂的映射逻辑,可以创建自定义值解析器:

public class FullNameResolver : IValueResolver<Customer, CustomerDto, string>
{
    public string Resolve(Customer source, CustomerDto destination, string destMember, ResolutionContext context)
    {
        return $"{source.FirstName} {source.LastName}";
    }
}

// 在映射配置中使用
CreateMap<Customer, CustomerDto>()
    .ForMember(dest => dest.FullName, 
               opt => opt.MapFrom<FullNameResolver>());

忽略属性

有时我们不希望映射某些属性:

CreateMap<Source, Destination>()
    .ForMember(dest => dest.PropertyToIgnore, opt => opt.Ignore());

双向映射

如果需要在两个类型之间进行双向映射,可以使用 ReverseMap 方法:

CreateMap<Customer, CustomerDto>()
    .ForMember(dest => dest.FullName, 
               opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}"))
    .ReverseMap()
    .ForMember(dest => dest.FirstName, 
               opt => opt.MapFrom(src => src.FullName.Split(' ')[0]))
    .ForMember(dest => dest.LastName, 
               opt => opt.MapFrom(src => src.FullName.Split(' ')[1]));

性能优化

编译映射

AutoMapper 提供了编译映射功能,可以显著提高映射性能:

var config = new MapperConfiguration(cfg => 
{
    cfg.CreateMap<Customer, CustomerDto>();
});

// 验证配置
config.AssertConfigurationIsValid();

// 编译映射
config.CompileMapping();

使用映射表达式

对于性能要求极高的场景,可以使用映射表达式:

var config = new MapperConfiguration(cfg => 
{
    cfg.CreateMap<Customer, CustomerDto>();
});

// 获取映射表达式
var customerDtoExpression = config.CreateMapper()
    .ConfigurationProvider
    .BuildExecutionPlan(typeof(Customer), typeof(CustomerDto));

// 在 LINQ 查询中使用
var customerDtos = dbContext.Customers
    .AsNoTracking()
    .ProjectTo<CustomerDto>(config)
    .ToList();

测试映射配置

确保映射配置正确是很重要的,AutoMapper 提供了验证配置的方法:

var config = new MapperConfiguration(cfg => 
{
    cfg.CreateMap<Customer, CustomerDto>();
});

// 验证所有映射配置
config.AssertConfigurationIsValid();

也可以编写单元测试来验证映射配置:

[Fact]
public void AutoMapper_Configuration_IsValid()
{
    var config = new MapperConfiguration(cfg => 
    {
        cfg.AddProfile<MappingProfile>();
    });
    
    config.AssertConfigurationIsValid();
}

实际应用案例

案例一:Web API 中的实体到 DTO 映射

在 Web API 中,我们通常需要将数据库实体转换为 DTO 以返回给客户端:

// 实体类
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }
    public int CategoryId { get; set; }
    public Category Category { get; set; }
    public DateTime CreatedAt { get; set; }
    public DateTime? UpdatedAt { get; set; }
    public bool IsDeleted { get; set; }
}

// DTO 类
public class ProductDto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }
    public string CategoryName { get; set; }
}

// 映射配置
public class ProductMappingProfile : Profile
{
    public ProductMappingProfile()
    {
        CreateMap<Product, ProductDto>()
            .ForMember(dest => dest.CategoryName, 
                      opt => opt.MapFrom(src => src.Category.Name));
    }
}

// 在控制器中使用
[HttpGet]
public ActionResult<IEnumerable<ProductDto>> GetProducts()
{
    var products = _repository.GetActiveProducts();
    return Ok(_mapper.Map<IEnumerable<ProductDto>>(products));
}

案例二:表单提交到领域模型的映射

当处理用户提交的表单数据时,我们需要将视图模型映射到领域模型:

// 视图模型
public class UserRegistrationViewModel
{
    public string Username { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public string ConfirmPassword { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime BirthDate { get; set; }
}

// 领域模型
public class User
{
    public int Id { get; set; }
    public string Username { get; set; }
    public string Email { get; set; }
    public string PasswordHash { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime BirthDate { get; set; }
    public DateTime CreatedAt { get; set; }
}

// 映射配置
public class UserMappingProfile : Profile
{
    public UserMappingProfile()
    {
        CreateMap<UserRegistrationViewModel, User>()
            .ForMember(dest => dest.PasswordHash, 
                      opt => opt.MapFrom(src => HashPassword(src.Password)))
            .ForMember(dest => dest.CreatedAt, 
                      opt => opt.MapFrom(src => DateTime.UtcNow))
            .ForMember(dest => dest.Id, opt => opt.Ignore());
    }
    
    private string HashPassword(string password)
    {
        // 实际应用中应使用安全的密码哈希算法
        return BCrypt.Net.BCrypt.HashPassword(password);
    }
}

// 在控制器中使用
[HttpPost]
public ActionResult Register(UserRegistrationViewModel model)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);
        
    var user = _mapper.Map<User>(model);
    _userService.Create(user);
    
    return CreatedAtAction(nameof(GetUser), new { id = user.Id }, null);
}

常见问题与解决方案

问题一:映射配置无效

AssertConfigurationIsValid() 方法抛出异常时,通常是因为存在未配置的属性映射。解决方案:

  1. 确保所有需要映射的属性都已配置
  2. 对于不需要映射的属性,使用 Ignore() 方法明确忽略
  3. 使用 CreateMap<Source, Destination>().ForAllMembers(opt => opt.Condition((src, dest, srcMember) => srcMember != null)); 忽略所有空值

问题二:循环引用

当对象之间存在循环引用时,AutoMapper 可能会陷入无限循环。解决方案:

  1. 在映射配置中使用 MaxDepth(n) 限制递归深度
  2. 在循环引用的一端使用 Ignore() 方法
CreateMap<Parent, ParentDto>()
    .ForMember(dest => dest.Children, opt => opt.MapFrom(src => src.Children))
    .MaxDepth(2);

CreateMap<Child, ChildDto>()
    .ForMember(dest => dest.Parent, opt => opt.Ignore());

问题三:性能问题

对于大量对象的映射,性能可能成为问题。解决方案:

  1. 使用 ProjectTo<T>() 在数据库查询级别执行映射
  2. 编译映射配置
  3. 考虑使用对象池来重用 Mapper 实例

最佳实践

  1. 组织映射配置:将映射配置组织到单独的 Profile 类中,按领域或功能分组
  2. 验证映射配置:使用 AssertConfigurationIsValid() 方法验证映射配置
  3. 使用依赖注入:在 ASP.NET Core 应用中使用依赖注入来管理 AutoMapper
  4. 避免深层嵌套映射:对于复杂对象图,考虑分解为多个映射步骤
  5. 编写单元测试:为映射配置编写单元测试,确保映射行为符合预期
  6. 使用 ProjectTo:在 LINQ 查询中使用 ProjectTo<T>() 方法提高性能

结论

AutoMapper 是一个强大的对象映射工具,可以显著减少样板代码,提高开发效率。通过本文介绍的基本用法、高级特性和最佳实践,你应该能够在自己的 C# 项目中有效地使用 AutoMapper 进行对象映射。

记住,虽然 AutoMapper 可以自动处理大多数映射场景,但对于复杂的业务逻辑,有时手动映射或自定义解析器可能是更好的选择。选择合适的工具和方法,取决于你的具体需求和场景。

参考资源

  • AutoMapper 官方文档
  • AutoMapper GitHub 仓库
  • AutoMapper 在 ASP.NET Core 中的使用

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2384971.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

提升开发运维效率:原力棱镜游戏公司的 Amazon Q Developer CLI 实践

引言 在当今快速发展的云计算环境中&#xff0c;游戏开发者面临着新的挑战和机遇。为了提升开发效率&#xff0c;需要更智能的工具来辅助工作流程。Amazon Q Developer CLI 作为亚马逊云科技推出的生成式 AI 助手&#xff0c;为开发者提供了一种新的方式来与云服务交互。 Ama…

@Column 注解属性详解

提示&#xff1a;文章旨在说明 Column 注解属性如何在日常开发中使用&#xff0c;数据库类型为 MySql&#xff0c;其他类型数据库可能存在偏差&#xff0c;需要注意。 文章目录 一、name 方法二、unique 方法三、nullable 方法四、insertable 方法五、updatable 方法六、column…

基于 ESP32 与 AWS 全托管服务的 IoT 架构:MQTT + WebSocket 实现设备-云-APP 高效互联

目录 一、总体架构图 二、设备端(ESP32)低功耗设计(适配 AWS IoT) 1.MQTT 设置(ESP32 连接 AWS IoT Core) 2.低功耗策略总结(ESP32) 三、云端架构(基于 AWS Serverless + IoT Core) 1.AWS IoT Core 接入 2.云端 → APP:WebSocket 推送方案 流程: 3.数据存…

unity在urp管线中插入事件

由于在urp下&#xff0c;打包后传统的相机事件有些无法正确执行&#xff0c;这时候我们需要在urp管线中的特定时机进行处理一些事件&#xff0c;需要创建继承ScriptableRenderPass和ScriptableRendererFeature的脚本&#xff0c;示例如下&#xff1a; PluginEventPass&#xf…

docker安装es连接kibana并安装分词器

使用Docker部署Elasticsearch、Kibana并安装分词器有以下主要优点&#xff1a; 1. 快速部署与一致性 一键式部署&#xff1a;通过Docker Compose可以快速搭建完整的ELK栈环境 环境一致性&#xff1a;确保开发、测试和生产环境完全一致&#xff0c;避免"在我机器上能运行…

线性回归中涉及的数学基础

线性回归中涉及的数学基础 本文详细地说明了线性回归中涉及到的主要的数学基础。 如果数学基础很扎实可以直接空降博文: 线性回归&#xff08;一&#xff09;-CSDN博客 一、概率、似然与概率密度函数 1. 概率&#xff08;Probability&#xff09; 定义&#xff1a;概率是描述…

如何计算VLLM本地部署Qwen3-4B的GPU最小配置应该是多少?多人并发访问本地大模型的GPU配置应该怎么分配?

本文一定要阅读我上篇文章&#xff01;&#xff01;&#xff01; 超详细VLLM框架部署qwen3-4B加混合推理探索&#xff01;&#xff01;&#xff01;-CSDN博客 本文是基于上篇文章遗留下的问题进行说明的。 一、本文解决的问题 问题1&#xff1a;我明明只部署了qwen3-4B的模型…

Attu下载 Mac版与Win版

通过Git地址下载 Mac 版选择对于的架构进行安装 其中遇到了安装不成功&#xff0c;文件损坏等问题 一般是两种情况导致 1.安装版本不对 2.系统权限限制 https://www.cnblogs.com/similar/p/11280162.html打开terminal执行以下命令 sudo spctl --master-disable安装包Git下载地…

V2X协议|如何做到“车联万物”?【无线通信小百科】

1、什么是V2X V2X&#xff08;Vehicle-to-Everything&#xff09;即“车联万物”&#xff0c;是一项使车辆能够与周围环境实现实时通信的前沿技术。它允许车辆与其他交通参与者和基础设施进行信息交互。通过V2X&#xff0c;车辆不仅具备“远程感知”能力&#xff0c;还能在更大…

[测试_3] 生命周期 | Bug级别 | 测试流程 | 思考

目录 一、软件测试的生命周期&#xff08;重点&#xff09; 1、软件测试 & 软件开发生命周期 &#xff08;1&#xff09;需求分析 &#xff08;2&#xff09;测试计划 &#xff08;3&#xff09;测试设计与开发 &#xff08;4&#xff09;测试执行 &#xff08;5&am…

RabbitMQ ⑤-顺序性保障 || 消息积压 || 幂等性

幂等性保障 幂等性&#xff08;Idempotency&#xff09; 是计算机科学和网络通信中的一个重要概念&#xff0c;指的是某个操作无论被执行多少次&#xff0c;所产生的效果与执行一次的效果相同。 应用程序的幂等性&#xff1a; 在应用程序中&#xff0c;幂等性就是指对一个系统…

java基础知识回顾1(可用于Java基础速通)考前,面试前均可用!

目录 一、初识java 二、基础语法 1.字面量 2.变量 3.关键字 4.标识符 声明&#xff1a;本文章根据黑马程序员b站教学视频做的笔记&#xff0c;可对应课程听&#xff0c;课程链接如下: 02、Java入门&#xff1a;初识Java_哔哩哔哩_bilibili 一、初识java Java是美国 sun 公…

云原生CICD-Tekton入门到精通

文章目录 一、Tekton介绍二、Tekton组件介绍三、执行流程四、安装Tekton管道五、安装Tekton Dashboard六、安装Tekton Cli七、运行单Task八、运行流水线九、在流水线中使用secret十、taskSpec、taskRef、pipelineRef、pipelineSpec使用pipelineRef与taskRef结合使用(推荐)pipel…

opencv 图像的平移和旋转

warpAffine函数讲解,图片可自行下载&#xff0c;也可用自己的图片 原图im 平移im_shifted 旋转im_rotated # 图像仿射变换 # 步骤&#xff1a; 读取图像 -> 创建仿射变换矩阵 -> 仿射变换计算 # 平移变换矩阵&#xff1a;一种写法&#xff0c;直接写死 # 旋转变…

IDEA2025版本使用Big Data Tools连接Linux上Hadoop的HDFS

目录 Windows的准备 1. 将与Linux上版本相同的hadoop压缩包解压到本地 ​编辑2.设置$HADOOP HOME环境变量指向:E:\hadoop-3.3.4 3.下载hadoop.dll和winutils.exe文件 4.将hadoop.dll和winutils.exe放入$HADOOP HOME/bin中 IDEA中操作 1.下载Big Data Tools插件 2.添加并连…

hysAnalyser特色的TS流编辑、剪辑和转存MP4功能说明

摘要 hysAnalyser 是一款特色的 MPEG-TS 数据分析工具&#xff0c;融合了常规TS文件的剪辑&#xff0c;转存功能&#xff0c;可用于平常的视频开发和测试。 本文详细阐述了对MPEG-TS 流的节目ID&#xff0c;名称&#xff0c;PID&#xff0c;时间戳&#xff0c;流类型&#xff…

Google机器学习实践指南(学习速率篇)

&#x1f525;Google机器学习核心概念精讲&#xff08;学习速率&#xff09; Google机器学习实战(7)-5分钟掌握学习速率。 学习速率&#xff1a;模型训练的关键超参数 学习速率是指在训练模型时用于梯度下降的一个标量。在每次迭代期间&#xff0c;梯度下降法都会将学习速率…

使用KubeKey快速部署k8s v1.31.8集群

实战环境涉及软件版本信息&#xff1a; 使用kubekey部署k8s 1. 操作系统基础配置 设置主机名、DNS解析、时钟同步、防火墙关闭、ssh免密登录等等系统基本设置 dnf install -y curl socat conntrack ebtables ipset ipvsadm 2. 安装部署 K8s 2.1 下载 KubeKey ###地址 https…

leetcode hot100:十四、解题思路大全:真·大全!

因为某大厂的算法没有撕出来&#xff0c;怒而整理该贴。部分题目有python版本的AC代码。本贴耗时4天呜呜呜 1.哈希 两数之和 给定一个整数数组 nums 和一个整数目标值 target&#xff0c;请你在该数组中找出 和为目标值 target 的那 两个 整数&#xff0c;并返回它们的数组下…

kali的简化安装

首先点击kali的官网 https://www.kali.org/get-kali/#kali-platforms 点击虚拟机版本 下载VMware版本的压缩包 解压后 点击 后缀名为 .vmx的文件 原始账号密码为 kali kali 这样安装 就不需要我们再去配置镜像 等等复杂操作了