Asp.NetCore 3.1 使用AutoMapper自动映射转换实体 DTO,Data2ViewModel
1:什么是AutoMapper?
下面为AutoMapper官方的解释:
AutoMapper是一个对象-对象映射器。对象-对象映射通过将一种类型的输入对象转换为另一种类型的输出对象来工作。
使AutoMapper变得有趣的是,它提供了一些有趣的约定,以免去搞清楚如何将类型A映射为类型B。只要类型B遵循AutoMapper既定的约定,就需要几乎零配置来映射两个类型。
2:使用AutoMapper有啥好处?
其实,这个比较好回答,通常在我们使用面向对象编程中,经常会遇到,ORM从数据库表中获取到比较多的字段,
这个时候我们止血药在页面展示比较少的字段,也可以起到节省流量,如果一两个实体的转换还好,成白上千N多地方都需要这样的操作,
还是手动一个一个的赋值实就大大降低了开发效率,这个时候AutoMapper就派上了用场!
3:怎么使用AutoMapper?
1:引入NuGet包 AutoMapper.Extensions.Microsoft.DependencyInjection 8.0.1最新版本即可,其他相关的依赖包会自动导入新增进来

2:定义好相关的model实体

using System; namespace WebApp.AutoMapperTestModel
{
// Entity类
public class SendMsg
{
public int mid { get; set; }
public string mTitle { get; set; }
public string mContent { get; set; }
public DateTime editTime { get; set; }
}
}

using System; namespace WebApp.AutoMapperTestModel
{
public class SendMsgViewModel
{
public int mid { get; set; }
public string mTitlw { get; set; }
public string mContent { get; set; }
public DateTime UpdateTime { get; set; }
}
}
3:注入AutoMapper的服务

4:使用AutoMapper创建实体之间的关系,定义一个来继承 Profile

5:在WebApi中较大使用AutoMapper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace WebApp.Controllers
{
using WebApp.AutoMapperTestModel;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[Controller]")]
public class DoAutoMapperController
{
private IMapper _mapper;
private List<SendMsg> sendMsgList { get; set; }
private SendMsg sendMsgOne { get; set; } public DoAutoMapperController(IMapper mapper)
{
_mapper = mapper;
sendMsgList = GetList();
sendMsgOne = GetSendMsg(); }
private List<SendMsg> GetList()
{
return new List<SendMsg> {
new SendMsg{ mid=,editTime=DateTime.Parse("1998-01-01"),mContent="你好我好大家好1",mTitle="T1"},
new SendMsg{ mid=,editTime=DateTime.Parse("1998-02-01"),mContent="你好我好大家好2",mTitle="T2"},
new SendMsg{ mid=,editTime=DateTime.Parse("1998-03-01"),mContent="你好我好大家好3",mTitle="T3"},
new SendMsg{ mid=,editTime=DateTime.Parse("1998-04-01"),mContent="你好我好大家好4",mTitle="T4"},
new SendMsg{ mid=,editTime=DateTime.Parse("1998-05-01"),mContent="你好我好大家好5",mTitle="T5"}
};
}
private SendMsg GetSendMsg()
{
return new SendMsg { mid = , editTime = DateTime.Parse("1998-01-01"), mContent = "你好我好大家好1", mTitle = "T1" };
} [HttpGet("Automapper")]
public ApiResultObject AutomapperOne()
{
ApiResultObject resultObject = new ApiResultObject();
try
{
var sendmsg = _mapper.Map<SendMsg, SendMsgViewModel>(sendMsgOne);
if (sendmsg != null)
{
resultObject.Data = sendmsg;
resultObject.Code = ResultCode.Success;
resultObject.Msg = "AutoMapper Success";
}
else
{
resultObject.Data = Enumerable.Empty<SendMsgViewModel>();
}
}
catch (Exception ex)
{
resultObject.Msg = $"发生异常:{ ex.Message}";
}
return resultObject; }
[HttpGet("AutomapperList")]
public ApiResultObject AutomapperList()
{
ApiResultObject resultObject = new ApiResultObject();
try
{
// List IEnumerable
IEnumerable<SendMsgViewModel> sendMsgViewModels = _mapper.Map<List<SendMsg>, IEnumerable<SendMsgViewModel>>(sendMsgList);
if (sendMsgViewModels != null && sendMsgViewModels.Any())
{
resultObject.Data = sendMsgViewModels;
resultObject.Code = ResultCode.Success;
resultObject.Msg = "AutoMapper Success";
}
else
{
resultObject.Data = Enumerable.Empty<SendMsgViewModel>();
}
}
catch (Exception ex)
{
resultObject.Msg = $"发生异常:{ ex.Message}";
}
return resultObject;
}
}
}
6:看测试结果:
两个表的定义的字存在不一致,映射的时候也没有指明关系,会导致相关字段没有值

映射并指明两者之间的属性关系之后:

最后来一个集合的映射测试,测试结果是ok的

7:最后还不过瘾,再来一波小菜:下面只是起到抛砖引玉的作用, 学友们可以根据自己的实际情况来使用扩展方法,直接点出,更是美美哒!!!

Asp.NetCore 3.1 使用AutoMapper自动映射转换实体 DTO,Data2ViewModel的更多相关文章
- AutoMapper自动映射
十年河东,十年河西,莫欺少年穷. 学无止境,精益求精. 不扯犊子,直接进入正题: AutoMapper自动映射常用于EF中,能很好的解决DTO和Model之间相互映射的问题.在未使用AutoMappe ...
- Mybaits 源码解析 (八)----- 全网最详细,没有之一:结果集 ResultSet 自动映射成实体类对象(上篇)
上一篇文章我们已经将SQL发送到了数据库,并返回了ResultSet,接下来就是将结果集 ResultSet 自动映射成实体类对象.这样使用者就无需再手动操作结果集,并将数据填充到实体类对象中.这可大 ...
- automapper 自动映射 集成asp.net Core2.1
学习博文:https://www.cnblogs.com/yan7/p/8085410.html 1.使用nuget 安装 <PackageReference Include="Aut ...
- AutoMapper 自动映射工具
先引用对应的DLL. 11.转换匿名对象 结合LINQ映射新的实体类. using System;using System.Collections.Generic;using System.Linq; ...
- AutoMapper在asp.netcore中的使用
# AutoMapper在asp.netcore中的使用 automapper 是.net 项目中针对模型之间转换映射的一个很好用的工具,不仅提高了开发的效率还使代码更加简洁,当然也是开源的,htt ...
- 【AutoMapper官方文档】DTO与Domin Model相互转换(中)
写在前面 AutoMapper目录: [AutoMapper官方文档]DTO与Domin Model相互转换(上) [AutoMapper官方文档]DTO与Domin Model相互转换(中) [Au ...
- Asp.NetCore之AutoMapper基础篇
应用场景 现在由于前后端技术的分离,后端程序员在使用ORM框架开发后台API接口的时候,往往会将数据库的"数据模型"直接提供给前端.而大多数时候,可能这些数据并不能够满足前端展示的 ...
- TransactionScope事务处理方法介绍及.NET Core中的注意事项 SQL Server数据库漏洞评估了解一下 预热ASP.NET MVC 的VIEW [AUTOMAPPER]反射自动注册AUTOMAPPER PROFILE
TransactionScope事务处理方法介绍及.NET Core中的注意事项 作者:依乐祝 原文链接:https://www.cnblogs.com/yilezhu/p/10170712.ht ...
- ASP.NET Core Web 应用程序系列(五)- 在ASP.NET Core中使用AutoMapper进行实体映射
本章主要简单介绍下在ASP.NET Core中如何使用AutoMapper进行实体映射.在正式进入主题之前我们来看下几个概念: 1.数据库持久化对象PO(Persistent Object):顾名思义 ...
随机推荐
- PythonFile对象的属性
PythonFile对象的属性: 一个文件被打开后,使用对象进行接收,接收的对象即为 File 对象 示例: ''' file.closed 返回true如果文件已被关闭,否则返回false file ...
- Python打开和关闭文件
Python打开和关闭文件: open(文件名,打开文件的模式[,寄存区的缓冲]): 文件名:字符串值 注:文件名带有后缀名 # 打开创建好的 test.txt 文件 f = open("t ...
- Django学习路33_url 地址及删除元素 delete() 和重定向 return redirect('路径')
保存日期 def create(request): '''新增一本图书''' # 1.创建BookInfo对象 b = BookInfo() b.btitle = '流星蝴蝶剑' b.bpub_d ...
- day19:os模块&shutil模块&tarfile模块
os模块:对系统进行操作(6+3) system popen listdir getcwd chdir environ / name sep linesep import os #### ...
- Python os.pathconf() 方法
概述 os.pathconf() 方法用于返回一个打开的文件的系统配置信息.高佣联盟 www.cgewang.com Unix 平台下可用. 语法 fpathconf()方法语法格式如下: os.fp ...
- PHP zip_entry_close() 函数
定义和用法 zip_entry_close() 函数关闭由 zip_entry_open() 函数打开的 zip 档案.高佣联盟 www.cgewang.com 语法 zip_entry_close( ...
- PDOStatement::fetch
PDOStatement::fetch — 从结果集中获取下一行(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0) 说明 语法 mixed PDOStatement:: ...
- Blob分析之board _components.hdev
*用立体方法分割板子组件的示例程序*Application program to illustrate the segmentation* of board _components.hdev wit ...
- C/C++编程笔记:C++入门知识丨从结构到类的演变
先来看看本节知识的结构图吧! 接下来我们就逐步来看一下所有的知识点: 结构的演化 C++中的类是从结构演变而来的, 所以我们可以称C++为”带类的C”. 结构发生质的演变 C++结构中可以定义函数, ...
- Docker管理工具之portainer
参考:https://www.cnblogs.com/frankdeng/p/9686735.html 1. 查询portainer镜像 命令:docker search portainer 实例: ...