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()
        {
            //实体转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

  • 13
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是在 .NET 6 ASP.NET Core Web API使用 AutoMap 的初始化和帮助类。 首先,你需要在你的项目中添加 AutoMap 的 NuGet 包。在 Visual Studio 中,右键点击项目,选择“Manage NuGet Packages”,然后搜索 AutoMap 并安装。 接下来,你需要创建一个帮助类来帮助你初始化 AutoMap。这个类可以是一个静态类,包含一个静态的初始化方法。这个初始化方法将会注册你的 Mapper 配置,以便在应用程序启动时自动执行。 ```csharp using AutoMapper; public static class AutoMapperConfig { public static void Initialize() { MapperConfiguration config = new MapperConfiguration(cfg => { // 在这里进行你的 Mapper 配置 cfg.CreateMap<SourceClass, DestinationClass>(); }); IMapper mapper = config.CreateMapper(); Mapper = mapper; } public static IMapper Mapper { get; private set; } } ``` 在你的 Startup.cs 文件中,你可以在 ConfigureServices 方法中调用这个初始化方法: ```csharp public void ConfigureServices(IServiceCollection services) { // 其他配置... AutoMapperConfig.Initialize(); } ``` 现在,你可以在你的控制器或其他服务中注入 IMapper 接口,使用 AutoMap 进行对象映射了。 ```csharp using AutoMapper; public class MyController : ControllerBase { private readonly IMapper _mapper; public MyController(IMapper mapper) { _mapper = mapper; } public IActionResult MyAction() { SourceClass source = new SourceClass(); DestinationClass destination = _mapper.Map<DestinationClass>(source); // 其他代码... } } ``` 这样,你就可以在 .NET 6 ASP.NET Core Web API使用 AutoMap 了。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值