热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

.net6API使用AutoMapper和DTO

AutoMapper,是一个转换工具,说到AutoMapper时,就不得不先说DTO,它叫做数据传输对象(DataTrans

        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中可以集成INotifyPropertyChanged
public 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中可以集成INotifyPropertyChanged
public 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一样,那么直接可以直接转换,不需要指定字段了
CreateMap().
ForMember(a => a.birthdayA, b => b.MapFrom(b => b.birthday))
.ForMember(a => a.nameA, b => b.MapFrom(b => b.name))
.ReverseMap();//ForMember指定转换的字段值,ReverseMap()意思是互相转换
//CreateMap().ForAllMembers(a => a.Ignore());
// CreateMap().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/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//添加AutoMapper
var automapperConfig = new MapperConfiguration(config =>
{
config.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention(); //Camel命名与Pascal命名的兼容,配置之后会映射property_name到PropertyName
config.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 _logger;
private readonly IMapper mapper; //注入
public WeatherForecastController(ILogger logger, IMapper mapper)
{
_logger = logger;
this.mapper = mapper;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable Get()
{
//将数据库的实体A,转化成界面需要的ADto,最终aDto是需要的值
A a = new A()
{
age = 1,
birthday = DateTime.Now,
id = 1,
name = "张三"
};
var aDto = mapper.Map(a);
//将界面的数据ADto,转换成实体A,最终a1是需要的值
ADto adto = new ADto()
{
ageA = 2,
birthdayA = DateTime.Now.AddDays(2),
id = 2,
nameA = "李四"
};
var a1 = mapper.Map(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



推荐阅读
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 本文介绍了iOS数据库Sqlite的SQL语句分类和常见约束关键字。SQL语句分为DDL、DML和DQL三种类型,其中DDL语句用于定义、删除和修改数据表,关键字包括create、drop和alter。常见约束关键字包括if not exists、if exists、primary key、autoincrement、not null和default。此外,还介绍了常见的数据库数据类型,包括integer、text和real。 ... [详细]
  • Imtryingtofigureoutawaytogeneratetorrentfilesfromabucket,usingtheAWSSDKforGo.我正 ... [详细]
  • 本文详细介绍了SQL日志收缩的方法,包括截断日志和删除不需要的旧日志记录。通过备份日志和使用DBCC SHRINKFILE命令可以实现日志的收缩。同时,还介绍了截断日志的原理和注意事项,包括不能截断事务日志的活动部分和MinLSN的确定方法。通过本文的方法,可以有效减小逻辑日志的大小,提高数据库的性能。 ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • Java序列化对象传给PHP的方法及原理解析
    本文介绍了Java序列化对象传给PHP的方法及原理,包括Java对象传递的方式、序列化的方式、PHP中的序列化用法介绍、Java是否能反序列化PHP的数据、Java序列化的原理以及解决Java序列化中的问题。同时还解释了序列化的概念和作用,以及代码执行序列化所需要的权限。最后指出,序列化会将对象实例的所有字段都进行序列化,使得数据能够被表示为实例的序列化数据,但只有能够解释该格式的代码才能够确定数据的内容。 ... [详细]
  • 开发笔记:加密&json&StringIO模块&BytesIO模块
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了加密&json&StringIO模块&BytesIO模块相关的知识,希望对你有一定的参考价值。一、加密加密 ... [详细]
  • 阿,里,云,物,联网,net,core,客户端,czgl,aliiotclient, ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • 使用Ubuntu中的Python获取浏览器历史记录原文: ... [详细]
  • r2dbc配置多数据源
    R2dbc配置多数据源问题根据官网配置r2dbc连接mysql多数据源所遇到的问题pom配置可以参考官网,不过我这样配置会报错我并没有这样配置将以下内容添加到pom.xml文件d ... [详细]
  • Spring学习(4):Spring管理对象之间的关联关系
    本文是关于Spring学习的第四篇文章,讲述了Spring框架中管理对象之间的关联关系。文章介绍了MessageService类和MessagePrinter类的实现,并解释了它们之间的关联关系。通过学习本文,读者可以了解Spring框架中对象之间的关联关系的概念和实现方式。 ... [详细]
  • Spring常用注解(绝对经典),全靠这份Java知识点PDF大全
    本文介绍了Spring常用注解和注入bean的注解,包括@Bean、@Autowired、@Inject等,同时提供了一个Java知识点PDF大全的资源链接。其中详细介绍了ColorFactoryBean的使用,以及@Autowired和@Inject的区别和用法。此外,还提到了@Required属性的配置和使用。 ... [详细]
author-avatar
一恒谢永泰_661
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有