論壇網(wǎng)站建設(shè)流程長(zhǎng)沙網(wǎng)站推廣工具
? ? ? ? AutoMapper,是一個(gè)轉(zhuǎn)換工具,說(shuō)到AutoMapper時(shí),就不得不先說(shuō)DTO,它叫做數(shù)據(jù)傳輸對(duì)象(Data Transfer Object)。
?
? ? ? ? 通俗的來(lái)說(shuō),DTO就是前端界面需要用的數(shù)據(jù)結(jié)構(gòu)和類(lèi)型,而我們經(jīng)常使用的數(shù)據(jù)實(shí)體,是數(shù)據(jù)庫(kù)需要用的數(shù)據(jù)結(jié)構(gòu)和類(lèi)型,它們2者負(fù)責(zé)的方向不一樣,經(jīng)常需要進(jìn)行轉(zhuǎn)化,那么此時(shí)AutoMapper就是一個(gè)轉(zhuǎn)換工具,它可以對(duì)數(shù)據(jù)實(shí)體和前端界面的數(shù)據(jù)進(jìn)行轉(zhuǎn)換,反之,也可以,這樣就加大了轉(zhuǎn)換的效率,如果不用AutoMapper時(shí),我們需要自己手寫(xiě)轉(zhuǎn)換,AutoMapper的目的就是提高轉(zhuǎn)換效率,不用寫(xiě)更多的判斷代碼了。
官網(wǎng)如下:
Getting Started Guide — AutoMapper documentation
1.創(chuàng)建一個(gè)可以運(yùn)行的.net6API程序
然后安裝AutoMapper
2. 建立一個(gè)Model文件夾,2個(gè)實(shí)體數(shù)據(jù),沒(méi)有什么意義,后面用于轉(zhuǎn)換
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.?建立一個(gè)Profile文件夾,2個(gè)Dto實(shí)體數(shù)據(jù),字段可以不一樣,也可以一樣,和之前的Model進(jìn)行轉(zhuǎn)換
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
此文件最重要,里面都是對(duì)實(shí)體類(lèi)和DTO進(jìn)行配置的,相互轉(zhuǎn)換的。
using AutoMapper;
using AutoMapperDemo.Model;namespace AutoMapperDemo.Profile
{public class AutoMapperProFile : MapperConfigurationExpression{//此文件的作用是,手動(dòng)增加配置文件,項(xiàng)目中需要什么,就加什么,并且對(duì)字段進(jìn)行映射匹配public AutoMapperProFile(){//映射關(guān)系//CreateMap<A, ADto>();//如果A和ADto一樣,那么直接可以直接轉(zhuǎn)換,不需要指定字段了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指定轉(zhuǎn)換的字段值,ReverseMap()意思是互相轉(zhuǎn)換//CreateMap<A, ADto>().ForAllMembers(a => a.Ignore());// CreateMap<B, BDto>().ReverseMap();}}
}
5.最后在Program.cs中注入
整體項(xiàng)目文件
?
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命名的兼容,配置之后會(huì)映射property_name到PropertyNameconfig.DestinationMemberNamingConvention = new PascalCaseNamingConvention();config.AddProfile(new AutoMapperProFile());});builder.Services.AddSingleton(automapperConfig.CreateMapper()); //只有一個(gè)單例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(){//將數(shù)據(jù)庫(kù)的實(shí)體A,轉(zhuǎn)化成界面需要的ADto,最終aDto是需要的值A(chǔ) a = new A(){age = 1,birthday = DateTime.Now,id = 1,name = "張三"};var aDto = mapper.Map<ADto>(a);//將界面的數(shù)據(jù)ADto,轉(zhuǎn)換成實(shí)體A,最終a1是需要的值A(chǔ)Dto 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();}}
}
總結(jié):AutoMapper還有一些復(fù)雜的轉(zhuǎn)換,這一切的轉(zhuǎn)換規(guī)則,都是根據(jù)業(yè)務(wù)來(lái)說(shuō)的,業(yè)務(wù)簡(jiǎn)單,甚至不用AutoMapper也可以。主要就是在AutoMapperProFile文件中,進(jìn)行修改和增加,以及使用的地方修改和增加。大部分都是2實(shí)體和DTO之間字段的匹配方式,值的轉(zhuǎn)換等等操作。
源碼:https://download.csdn.net/download/u012563853/87454728