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

相关文章

使用animation.css库快速实现CSS3旋转动画效果

《使用animation.css库快速实现CSS3旋转动画效果》随着Web技术的不断发展,动画效果已经成为了网页设计中不可或缺的一部分,本文将深入探讨animation.css的工作原理,如何使用以及... 目录1. css3动画技术简介2. animation.css库介绍2.1 animation.cs

使用雪花算法产生id导致前端精度缺失问题解决方案

《使用雪花算法产生id导致前端精度缺失问题解决方案》雪花算法由Twitter提出,设计目的是生成唯一的、递增的ID,下面:本文主要介绍使用雪花算法产生id导致前端精度缺失问题的解决方案,文中通过代... 目录一、问题根源二、解决方案1. 全局配置Jackson序列化规则2. 实体类必须使用Long封装类3.

Python文件操作与IO流的使用方式

《Python文件操作与IO流的使用方式》:本文主要介绍Python文件操作与IO流的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、python文件操作基础1. 打开文件2. 关闭文件二、文件读写操作1.www.chinasem.cn 读取文件2. 写

PyQt6中QMainWindow组件的使用详解

《PyQt6中QMainWindow组件的使用详解》QMainWindow是PyQt6中用于构建桌面应用程序的基础组件,本文主要介绍了PyQt6中QMainWindow组件的使用,具有一定的参考价值,... 目录1. QMainWindow 组php件概述2. 使用 QMainWindow3. QMainW

使用Python自动化生成PPT并结合LLM生成内容的代码解析

《使用Python自动化生成PPT并结合LLM生成内容的代码解析》PowerPoint是常用的文档工具,但手动设计和排版耗时耗力,本文将展示如何通过Python自动化提取PPT样式并生成新PPT,同时... 目录核心代码解析1. 提取 PPT 样式到 jsON关键步骤:代码片段:2. 应用 JSON 样式到

java变量内存中存储的使用方式

《java变量内存中存储的使用方式》:本文主要介绍java变量内存中存储的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、介绍2、变量的定义3、 变量的类型4、 变量的作用域5、 内存中的存储方式总结1、介绍在 Java 中,变量是用于存储程序中数据

关于Mybatis和JDBC的使用及区别

《关于Mybatis和JDBC的使用及区别》:本文主要介绍关于Mybatis和JDBC的使用及区别,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、JDBC1.1、流程1.2、优缺点2、MyBATis2.1、执行流程2.2、使用2.3、实现方式1、XML配置文件

macOS Sequoia 15.5 发布: 改进邮件和屏幕使用时间功能

《macOSSequoia15.5发布:改进邮件和屏幕使用时间功能》经过常规Beta测试后,新的macOSSequoia15.5现已公开发布,但重要的新功能将被保留到WWDC和... MACOS Sequoia 15.5 正式发布!本次更新为 Mac 用户带来了一系列功能强化、错误修复和安全性提升,进一步增

Java资源管理和引用体系的使用详解

《Java资源管理和引用体系的使用详解》:本文主要介绍Java资源管理和引用体系的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、Java的引用体系1、强引用 (Strong Reference)2、软引用 (Soft Reference)3、弱引用 (W

ubuntu系统使用官方操作命令升级Dify指南

《ubuntu系统使用官方操作命令升级Dify指南》Dify支持自动化执行、日志记录和结果管理,适用于数据处理、模型训练和部署等场景,今天我们就来看看ubuntu系统中使用官方操作命令升级Dify的方... Dify 是一个基于 docker 的工作流管理工具,旨在简化机器学习和数据科学领域的多步骤工作流。