.net6API使用AutoMapper和DTO
AutoMapper,是一个转换工具,说到AutoMapper时,就不得不先说DTO,它叫做数据传输对象(Data Transfer Object)。
通俗的来说,DTO就是前端界面需要用的数据结构和类型,而我们经常使用的数据实体,是数据库需要用的数据结构和类型,它们2者负责的方向不一样,经常需要进行转化,那么此时AutoMapper就是一个转换工具,它可以对数据实体和前端界面的数据进行转换,反之,也可以,这样就加大了转换的效率,如果不用AutoMapper时,我们需要自己手写转换,AutoMapper的目的就是提高转换效率,不用写更多的判断代码了。
官网如下:
Getting Started Guide — AutoMapper documentation
1.创建一个可以运行的.net6API程序
然后安装AutoMapper
2. 建立一个Model文件夹,2个实体数据,没有什么意义,后面用于转换
A.cs
namespace AutoMapperDemo.Model
{public class A{public int id { get; set; }public string? name { get; set; }public int age { get; set; }public DateTime birthday { get; set; }}
}
B.cs
namespace AutoMapperDemo.Model
{public class B{public int id { get; set; }public string ? school { get; set; }public int code { get; set; }}
}
3. 建立一个Profile文件夹,2个Dto实体数据,字段可以不一样,也可以一样,和之前的Model进行转换
dto里面的字段,就是前端需要显示的字段
ADto.cs
namespace AutoMapperDemo.Model
{public class ADto{//wpf中可以集成INotifyPropertyChangedpublic int id { get; set; }public string? nameA { get; set; }public int ageA { get; set; }public DateTime birthdayA { get; set; }}
}
BDto.cs
namespace AutoMapperDemo.Model
{public class BDto{//wpf中可以集成INotifyPropertyChangedpublic int id { get; set; }public string ? schoolB { get; set; }public int codeB { get; set; }}
}
4. 建立AutoMapperProFile.cs
此文件最重要,里面都是对实体类和DTO进行配置的,相互转换的。
using AutoMapper;
using AutoMapperDemo.Model;namespace AutoMapperDemo.Profile
{public class AutoMapperProFile : MapperConfigurationExpression{//此文件的作用是,手动增加配置文件,项目中需要什么,就加什么,并且对字段进行映射匹配public AutoMapperProFile(){//映射关系//CreateMap<A, ADto>();//如果A和ADto一样,那么直接可以直接转换,不需要指定字段了CreateMap<A, ADto>().ForMember(a => a.birthdayA, b => b.MapFrom(b => b.birthday)).ForMember(a => a.nameA, b => b.MapFrom(b => b.name)).ReverseMap();//ForMember指定转换的字段值,ReverseMap()意思是互相转换//CreateMap<A, ADto>().ForAllMembers(a => a.Ignore());// CreateMap<B, BDto>().ReverseMap();}}
}
5.最后在Program.cs中注入
整体项目文件
using AutoMapper;
using AutoMapperDemo.Profile;namespace AutoMapperDemo
{public class Program{public static void Main(string[] args){var builder = WebApplication.CreateBuilder(args);// Add services to the container.builder.Services.AddControllers();// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbucklebuilder.Services.AddEndpointsApiExplorer();builder.Services.AddSwaggerGen();//添加AutoMappervar automapperConfig = new MapperConfiguration(config =>{config.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention(); //Camel命名与Pascal命名的兼容,配置之后会映射property_name到PropertyNameconfig.DestinationMemberNamingConvention = new PascalCaseNamingConvention();config.AddProfile(new AutoMapperProFile());});builder.Services.AddSingleton(automapperConfig.CreateMapper()); //只有一个单例var app = builder.Build();// Configure the HTTP request pipeline.if (app.Environment.IsDevelopment()){app.UseSwagger();app.UseSwaggerUI();}app.UseHttpsRedirection();app.UseAuthorization();app.MapControllers();app.Run();}}
}
6.使用,如图所示
using AutoMapper;
using AutoMapperDemo;
using AutoMapperDemo.Model;
using Microsoft.AspNetCore.Mvc;
using System.Reflection;namespace AutoMapperDemo.Controllers
{[ApiController][Route("[controller]")]public class WeatherForecastController : ControllerBase{private static readonly string[] Summaries = new[]{"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"};private readonly ILogger<WeatherForecastController> _logger;private readonly IMapper mapper; //注入public WeatherForecastController(ILogger<WeatherForecastController> logger, IMapper mapper){_logger = logger;this.mapper = mapper;}[HttpGet(Name = "GetWeatherForecast")]public IEnumerable<WeatherForecast> Get(){//将数据库的实体A,转化成界面需要的ADto,最终aDto是需要的值A a = new A(){age = 1,birthday = DateTime.Now,id = 1,name = "张三"};var aDto = mapper.Map<ADto>(a);//将界面的数据ADto,转换成实体A,最终a1是需要的值ADto adto = new ADto(){ageA = 2,birthdayA = DateTime.Now.AddDays(2),id = 2,nameA = "李四"};var a1 = mapper.Map<A>(adto);return Enumerable.Range(1, 5).Select(index => new WeatherForecast{Date = DateTime.Now.AddDays(index),TemperatureC = Random.Shared.Next(-20, 55),Summary = Summaries[Random.Shared.Next(Summaries.Length)]}).ToArray();}}
}
总结:AutoMapper还有一些复杂的转换,这一切的转换规则,都是根据业务来说的,业务简单,甚至不用AutoMapper也可以。主要就是在AutoMapperProFile文件中,进行修改和增加,以及使用的地方修改和增加。大部分都是2实体和DTO之间字段的匹配方式,值的转换等等操作。
源码:https://download.csdn.net/download/u012563853/87454728