Asp.NetCore 3.1 使用AutoMapper自动映射转换实体 DTO,Data2ViewModel

1:什么是AutoMapper?

下面为AutoMapper官方的解释:

AutoMapper是一个对象-对象映射器。对象-对象映射通过将一种类型的输入对象转换为另一种类型的输出对象来工作。

使AutoMapper变得有趣的是,它提供了一些有趣的约定,以免去搞清楚如何将类型A映射为类型B。只要类型B遵循AutoMapper既定的约定,就需要几乎零配置来映射两个类型。

附上官网地址://docs.automapper.org/en/stable/Getting-started.html

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; }
    }
}

View Code

 1 using System;
 2 
 3 namespace WebApp.AutoMapperTestModel
 4 {
 5     public class SendMsgViewModel
 6     {
 7         public int mid { get; set; }
 8         public string mTitlw { get; set; }
 9         public string mContent { get; set; }
10         public DateTime UpdateTime { get; set; }
11     }
12 }

View Code

3:注入AutoMapper的服务

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

5:在WebApi中较大使用AutoMapper

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 
 6 namespace WebApp.Controllers
 7 {
 8     using WebApp.AutoMapperTestModel;
 9     using AutoMapper;
10     using Microsoft.AspNetCore.Mvc;
11     [ApiController]
12     [Route("api/[Controller]")]
13     public class DoAutoMapperController
14     {
15         private IMapper _mapper;
16         private List<SendMsg> sendMsgList { get; set; }
17         private SendMsg sendMsgOne { get; set; }
18 
19         public DoAutoMapperController(IMapper mapper)
20         {
21             _mapper = mapper;
22             sendMsgList = GetList();
23             sendMsgOne = GetSendMsg();
24 
25         }
26         private List<SendMsg> GetList()
27         {
28             return new List<SendMsg> {
29                  new SendMsg{ mid=110,editTime=DateTime.Parse("1998-01-01"),mContent="你好我好大家好1",mTitle="T1"},
30                  new SendMsg{ mid=111,editTime=DateTime.Parse("1998-02-01"),mContent="你好我好大家好2",mTitle="T2"},
31                  new SendMsg{ mid=112,editTime=DateTime.Parse("1998-03-01"),mContent="你好我好大家好3",mTitle="T3"},
32                  new SendMsg{ mid=113,editTime=DateTime.Parse("1998-04-01"),mContent="你好我好大家好4",mTitle="T4"},
33                  new SendMsg{ mid=114,editTime=DateTime.Parse("1998-05-01"),mContent="你好我好大家好5",mTitle="T5"}
34             };
35         }
36         private SendMsg GetSendMsg()
37         {
38             return new SendMsg { mid = 110, editTime = DateTime.Parse("1998-01-01"), mContent = "你好我好大家好1", mTitle = "T1" };
39         }
40 
41         [HttpGet("Automapper")]
42         public ApiResultObject AutomapperOne()
43         {
44             ApiResultObject resultObject = new ApiResultObject();
45             try
46             {
47                 var sendmsg = _mapper.Map<SendMsg, SendMsgViewModel>(sendMsgOne);
48                 if (sendmsg != null)
49                 {
50                     resultObject.Data = sendmsg;
51                     resultObject.Code = ResultCode.Success;
52                     resultObject.Msg = "AutoMapper Success";
53                 }
54                 else
55                 {
56                     resultObject.Data = Enumerable.Empty<SendMsgViewModel>();
57                 }
58             }
59             catch (Exception ex)
60             {
61                 resultObject.Msg = $"发生异常:{ ex.Message}";
62             }
63             return resultObject;
64 
65         }
66         [HttpGet("AutomapperList")]
67         public ApiResultObject AutomapperList()
68         {
69             ApiResultObject resultObject = new ApiResultObject();
70             try
71             {
72                 //                                                                      List IEnumerable
73                 IEnumerable<SendMsgViewModel> sendMsgViewModels = _mapper.Map<List<SendMsg>, IEnumerable<SendMsgViewModel>>(sendMsgList);
74                 if (sendMsgViewModels != null && sendMsgViewModels.Any())
75                 {
76                     resultObject.Data = sendMsgViewModels;
77                     resultObject.Code = ResultCode.Success;
78                     resultObject.Msg = "AutoMapper Success";
79                 }
80                 else
81                 {
82                     resultObject.Data = Enumerable.Empty<SendMsgViewModel>();
83                 }
84             }
85             catch (Exception ex)
86             {
87                 resultObject.Msg = $"发生异常:{ ex.Message}";
88             }
89             return resultObject;
90         }
91     }
92 }

View Code

6:看测试结果:

两个表的定义的字存在不一致,映射的时候也没有指明关系,会导致相关字段没有值

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

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

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