ASP.NET CORE 中使用AutoMapper进行对象映射

ASP.NET CORE 中使用AutoMapper进行对象映射

1、什么是AutoMapper?

AutoMapper是基于对象到对象约定的映射工具,常用于(但并不仅限制于)把复杂的对象模型转为DTO,一般用于ViewModel模式和跨服务范畴。

AutoMapper给用户提供了便捷的配置API,就像使用约定来完成自动映射那样。

AutoMapper包含以下功能:平展、投影、配置验证、列表和数组、嵌套映射、自定义类型转换程序、自定义值转换程序 、自定义值格式程序 、Null值替换

AutoMapper是一款单向映射器。这意味着它并没有内建映射对象支持来回写至原始源,除非用户在更新映射对象之后明确地创建逆向反射。这需要 通过设计完成,因为让DTO回写到,比方说:域模型或其他东西,就会更改它的持久性,同时人们也认为它是反模式的。在这种解决方案中,命令消息在双向映射 中往往是更好的选择。然而,在某些特定环境中,有人可能会为双向映射辩解,比如:非常简单的CRUD应用程序。一个支持双向映射的框架就是Glue。

2、在ASP.NET CORE中使用AutoMapper

在程序包管理控制台中执行命令安装依赖包:

PM> Install-Package AutoMapper -Version 8.1.1
PM> Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection -Version 6.1.1

 ②使用依赖关系注入从应用中引用的服务

在Startup类的ConfigureServices()方法中调用AddAutoMapper()服务:

1 public void ConfigureServices(IServiceCollection services)
2 {
3     services.AddAutoMapper();
4 }

③创建AutoMapper映射规则

添加AutoMapperConfigs类,继承Profile类

 1 using AutoMapper;
 2 using CodeFirst.Models;
 3 using DAL;
 4 
 5 namespace CodeFirst.Common
 6 {
 7     public class AutoMapperConfigs : Profile
 8     {
 9         //添加实体映射关系
10         public AutoMapperConfigs()
11         {
12             CreateMap<MainModel, MainInfoResult>();  //MainModel转MainInfoResult
13             CreateMap<MainInfoResult, MainModel>();  //MainInfoResult转MainModel
14         }
15     }
16 }

 ④在构造函数中注入IMapper

1 public class LoginController : Controller
2 {
3     private IMapper _mapper;
4 
5     public LoginController(IMapper mapper)
6     {
7         _mapper = mapper;
8     }
9 }

⑤使用AutoMapper进行对象转换

单个对象转换

1 public ActionResult RegistSend(MainModel model)
2 {
3     var dto = _mapper.Map<MainInfoResult>(model);//MainModel 转MainInfoResult
4     var re = _userdal.RegistSend(dto);//传入的对象为MainInfoResult
5     return Json(new { status = re.Status, message = re.Message });
6 }

集合转换

public List<Student> GetStudentList()
   {
       //模拟数据
       var StuList = new List<StuInfo>()
       {
           new StuInfo(){ Id=1,Name="张三",Sex="",Age=18 },
           new StuInfo(){ Id=2,Name="李四",Sex="",Age=19 },
           new StuInfo(){ Id=3,Name="王五",Sex="",Age=18 },
       };
       //对象集合转Dto集合.
       var Students = _mapper.Map<List<Student>>(StuList);
       return Students;
   }

AutoMapper功能十分强大,支持属性名不同,NULL值替换等等,在此只介绍简单的常用方法,有关详情见AutoMapper官网地址:http://automapper.org/

猜你喜欢

转载自www.cnblogs.com/gygg/p/11286869.html