asp.net core webapi AutoMapper使用

2023-12-27 21:04

本文主要是介绍asp.net core webapi AutoMapper使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.AutoMapper介绍:

AutoMapper是一个.NET库,用于简化对象之间的映射。它可以帮助开发人员在不同类型之间进行自动转换,从而减少重复的手动映射代码。

使用AutoMapper,开发人员可以定义映射规则,然后该库会自动执行对象之间的映射。这使得在应用程序中对数据进行转换和映射变得更加简单和高效。

下面是AutoMapper的一些常见功能:

  1. 对象到对象的映射:简化了从一个对象类型到另一个对象类型的转换。

  2. 集合的映射:可以自动映射集合中的对象,减少了手动迭代和映射的工作。

  3. 可配置的映射规则:开发人员可以定义自定义的映射规则,以满足特定的需求。

  4. 灵活的映射选项:AutoMapper提供了许多选项和配置,以满足各种映射需求。

总的来说,AutoMapper是一个非常有用的库,可以帮助.NET开发人员简化对象之间的映射工作,提高代码的可读性和可维护性。

2.使用

2.1安装automapper nuget包

<PackageReference Include="AutoMapper" Version="12.0.1" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />

2.2 创建对应的实体和dto

namespace webapi.Data
{public class City{public int Id { get; set; }public string CityName { get; set; }public Area area { get; set; }}public class Area{public int AreaId { get; set; }public string AreaName { get; set; }}public class CityDto{public int Id { get; set; }public string CityName { get; set; }public AreaDto area { get; set; }}public class AreaDto{public int AreaId1 { get; set; }public string AreaName1 { get; set; }}//------------//public class City1{public int Id { get; set; }public string CityName { get; set; }public List<Area> area { get; set; }}public class AreaDtos{public int AreaId { get; set; }public string AreaName { get; set; }}public class CityDto1{public int Id { get; set; }public string CityName { get; set; }public List<AreaDtos> area { get; set; }}//------//public class People{public string T_Name { get; set; }public int T_Age { get; set; }public string Address_tb1 { get; set; }public string sex_tb1 { get; set; }}public class ChildDto{public string Name { get; set; }public int Age { get; set; }public string Address { get; set; }public string sex { get; set; }}
}namespace webapi.Data
{public class Stu{public int Id { get; set; }public string Name { get; set; }public string Address { get; set; }public string NickName { get; set; }public bool Sex { get; set; }}public class Stu1{public int No { get; set; }public string Name { get; set; }public string Address { get; set; }public string NickName { get; set; }public bool Sex { get; set; }}public class Stu2{public int Id { get; set; }public string Name { get; set; }public string Address { get; set; }//[JsonIgnore]public string NickName { get; set; }public bool Sex { get; set; }}
}
namespace webapi.Data
{public class StuDto{public int Id { get; set; }public string Name { get; set; }public string Address { get; set; }public string NickName { get; set; }public bool Sex { get; set; }}public class StuDto1{public int Id { get; set; }public string Name { get; set; }public string Address { get; set; }public string NickName { get; set; }public string Sex { get; set; }}public class StuDto2{public int Id { get; set; }public string Name { get; set; }public string Address { get; set; }public string NickName { get; set; }public bool Sex { get; set; }}
}

2.3 创建配置类

using AutoMapper;
using webapi.Data;namespace webapi.Mapping
{/// <summary>/// 对象映射/// </summary>public class CustomProfile : Profile{public CustomProfile(){//实体转DTOCreateMap<Stu, StuDto>();//DTO转实体CreateMap<StuDto, Stu>();//实体转dto字段名不相同 stu1是No studto 是Id//stuDto的Id和Stu1的No字段进行映射CreateMap<Stu1, StuDto>().ForMember(x => x.Id, p => p.MapFrom(p => p.No));//实体转DTO,数据内容进行转换 Stu2 性别是 1和0 转成 StuDto1 中的男和女CreateMap<Stu1, StuDto1>().ForMember(x => x.Sex, p => p.MapFrom(p => p.Sex == true ? "男" : "女"));//忽略字段//Dto转实体忽略IdCreateMap<StuDto2, Stu2>().ForMember(x => x.Id, p => p.Ignore());//实体嵌套实体映射dtoCreateMap<City, CityDto>();CreateMap<Area, AreaDto>().ForMember(x => x.AreaId1, p => p.MapFrom(p => p.AreaId)).ForMember(x => x.AreaName1, p => p.MapFrom(p => p.AreaName));//实体嵌SS套实体集合映射CreateMap<City1, CityDto1>();CreateMap<Area, AreaDtos>();//映射时匹配前缀RecognizePrefixes("T_");//映射匹配后缀RecognizePostfixes("_tb1");CreateMap<People, ChildDto>();}}
}

2.4注入automapper服务

  builder.Services.AddAutoMapper(typeof(CustomProfile));

2.5编写控制器类

using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Net.Http.Headers;
using webapi.Data;namespace webapi.Controllers;/// <summary>
/// automappe测试
/// </summary>
[ApiController]
[Route("[controller]/[action]")]
public class MapperTestController : ControllerBase
{public readonly IMapper _mapper;/// <summary>/// 注入服务/// </summary>public MapperTestController(IMapper mapper){_mapper = mapper;}/// <summary>/// 实体转DTO/// </summary>///<remarks></remarks>/// <returns></returns>[HttpGet]public ActionResult<StuDto> EntityToDto(){Stu stu = new Stu(){Id = 1,Name = "Test",Address = "江苏",NickName = "pp00",Sex = true};//StuDto stuDto = _mapper.Map<StuDto>(stu);// _mapper.Map<StuDto>(stu)和 _mapper.Map(stu, new StuDto())效果一样StuDto stuDto = _mapper.Map(stu, new StuDto());return stuDto;}/// <summary>/// DTO转实体/// </summary>/// <returns></returns>[HttpGet]public ActionResult<Stu> DtoToEntity(){StuDto stuDto = new StuDto(){Id = 1,Name = "Test",Address = "江苏",NickName = "pp00",Sex = true};Stu stu = _mapper.Map<Stu>(stuDto);return stu;}/// <summary>/// 实体转dto字段名不同/// </summary>/// <remarks>Stu1 No stuDto Id</remarks>/// <returns></returns>[HttpGet]public ActionResult<StuDto> FieldsNotSame(){Stu1 stu = new Stu1(){No = 1,Name = "Test",Address = "江苏",NickName = "pp00",Sex = true};StuDto stuDto = _mapper.Map(stu, new StuDto());return stuDto;}/// <summary>///实体转DTO,数据内容进行转换 Stu2 性别是 1和0 转成 StuDto1 中的男和女/// </summary>/// <returns></returns>[HttpGet]public ActionResult<StuDto1> ContentConverter(){Stu1 stu = new Stu1(){No = 1,Name = "Test",Address = "江苏",NickName = "pp00",Sex = true};StuDto1 stuDto1 = _mapper.Map<StuDto1>(stu);return stuDto1;}/// <summary>/// 忽略字段/// 被忽略的字段会采用默认值/// </summary>/// <returns></returns>[HttpGet]public ActionResult<Stu2> IgnoreFile(){StuDto2 stu = new StuDto2(){Id = 100,Name = "Test",Address = "江西",NickName = "Test",Sex = true};Stu2 stu2 = _mapper.Map<Stu2>(stu);return stu2;}/// <summary>/// list集合实体转list集合dto/// </summary>/// <returns></returns>[HttpGet]public ActionResult<List<StuDto>> AttachEntityToDto(){List<Stu> stuls = new List<Stu>() {new Stu(){Id = 1,Name = "Test",Address = "江苏",NickName = "pp00",Sex = true},new Stu() {Id = 2,Name = "Test",Address = "江苏",NickName = "pp00",Sex = true},new Stu() {Id = 3,Name = "Test",Address = "江苏",NickName = "pp00",Sex = true},};var result = _mapper.Map<List<StuDto>>(stuls);return result;}/// <summary>/// 嵌套映射单实体/// 如果嵌套的单实体字段和dto相同,就只需配置外层实体的映射/// </summary>/// <returns></returns>[HttpGet]public ActionResult<CityDto> NestedMapping(){City city = new City(){Id = 1,CityName = "南京",area = new Area(){AreaId = 1001,AreaName = "栖霞区"}};CityDto cityDto = _mapper.Map<CityDto>(city);return cityDto;}/// <summary>/// 嵌套映射list集合/// 需要配置外表的映射关系和嵌套list集合表的映射关系/// </summary>/// <returns></returns>[HttpGet]public ActionResult<CityDto1> NestedListMapping(){City1 city = new City1(){Id = 1,CityName = "南京",area = new List<Area>(){new Area() {AreaId=1001,AreaName="雨花台"},new Area() {AreaId=1002,AreaName="建业"},}};CityDto1 cityDto = _mapper.Map<CityDto1>(city);return cityDto;}/// <summary>/// 映射匹配前缀和后缀/// </summary>/// <returns></returns>[HttpGet]public ActionResult<ChildDto> Recognizeprefixes(){People p1 = new People(){T_Age = 10,T_Name = "Test",Address_tb1 = "江西",sex_tb1 = "男"};return _mapper.Map<ChildDto>(p1);}
}

上面的几种配置是,比较常用的,更多的配置自己可以去自己摸索。
end

这篇关于asp.net core webapi AutoMapper使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/544279

相关文章

Conda与Python venv虚拟环境的区别与使用方法详解

《Conda与Pythonvenv虚拟环境的区别与使用方法详解》随着Python社区的成长,虚拟环境的概念和技术也在不断发展,:本文主要介绍Conda与Pythonvenv虚拟环境的区别与使用... 目录前言一、Conda 与 python venv 的核心区别1. Conda 的特点2. Python v

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

C#中Guid类使用小结

《C#中Guid类使用小结》本文主要介绍了C#中Guid类用于生成和操作128位的唯一标识符,用于数据库主键及分布式系统,支持通过NewGuid、Parse等方法生成,感兴趣的可以了解一下... 目录前言一、什么是 Guid二、生成 Guid1. 使用 Guid.NewGuid() 方法2. 从字符串创建

Python使用python-can实现合并BLF文件

《Python使用python-can实现合并BLF文件》python-can库是Python生态中专注于CAN总线通信与数据处理的强大工具,本文将使用python-can为BLF文件合并提供高效灵活... 目录一、python-can 库:CAN 数据处理的利器二、BLF 文件合并核心代码解析1. 基础合

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四