asp.net core webapi AutoMapper使用

发布时间:2023年12月26日

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()
        {
            //实体转DTO
            CreateMap<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转实体忽略Id
            CreateMap<StuDto2, Stu2>().ForMember(x => x.Id, p => p.Ignore());
            //实体嵌套实体映射dto
            CreateMap<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

文章来源:https://blog.csdn.net/qq_41942413/article/details/135219981
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。