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):顾名思义 ...
随机推荐
- PHP atan2() 函数
实例 通过 atan2() 函数返回两个变量的反正切: <?phpecho(atan2(0.50,0.50) . "<br>");echo(atan2(-0.50 ...
- luogu P4726 【模板】多项式指数函数 多项式 exp 牛顿迭代 泰勒展开
LINK:多项式 exp 做多项式的题 简直在嗑药. 前置只是 泰勒展开 这个东西用于 对于一个函数f(x) 我们不好得到 其在x处的取值. 所以另外设一个函数g(x) 来在x点处无限逼近f(x). ...
- AsyncTask被废弃了,换Coroutine吧
本文主要是学习笔记,有版权问题还请告知删文 鸣谢:guolin@第一行代码(第三版) 你是否也在最近的代码中看见了 AsyncTask 被一条横杠划掉了 这表明--他要被Google放弃了 Googl ...
- 5个Python特性 越早知道越好的
Kirill Sharkovski 发布在 Unsplash 杂志上的照片 AI开发者按,Python 是近十年来兴起的编程语言,并且被证明是一种非常强大的语言.我用 Python 构建了很多应用程序 ...
- Docker 搭建 GitLab
Docker 搭建 GitLab 步骤 # 创建目录 mkdir -p /usr/local/gitlab && cd /usr/local/gitlab # 创建映射目录 mkdir ...
- Springboot快速入门篇,图文并茂
Springboot快速入门篇,图文并茂 文章已托管到GitHub,大家可以去GitHub查看阅读,欢迎老板们前来Star!搜索关注微信公众号 [码出Offer] 领取各种学习资料! image-20 ...
- 【API进阶之路】无法想象!大龄码农的硬盘里有这么多宝藏
摘要:通过把所需建立的工具库做成云容器化应用,用CCE引擎,通过API网关调用云容器引擎中的容器应用.不仅顺应了云原生的发展趋势,还能随时弹性扩容,满足公司规模化发展的需求. 公司开完年中会后,大家的 ...
- C#LeetCode刷题-随机数
随机数篇 # 题名 刷题 通过率 难度 470 用 Rand7() 实现 Rand10() 34.4% 中等 478 在圆内随机生成点 22.8% 中等 497 非重叠矩形中的随机点 22 ...
- C#LeetCode刷题之#443-压缩字符串(String Compression)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3943 访问. 给定一组字符,使用原地算法将其压缩. 压缩后的长度 ...
- C#LeetCode刷题之#231-2的幂(Power of Two)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3858 访问. 给定一个整数,编写一个函数来判断它是否是 2 的幂 ...