翼度科技»论坛 编程开发 .net 查看内容

ASP.NET Core MVC 从入门到精通之自动映射(一)

5

主题

5

帖子

15

积分

新手上路

Rank: 1

积分
15
随着技术的发展,ASP.NET Core MVC也推出了好长时间,经过不断的版本更新迭代,已经越来越完善,本系列文章主要讲解ASP.NET Core MVC开发B/S系统过程中所涉及到的相关内容,适用于初学者,在校毕业生,或其他想从事ASP.NET Core MVC 系统开发的人员。 经过前几篇文章的讲解,初步了解ASP.NET Core MVC项目创建,启动运行,以及命名约定,创建控制器,视图,模型,接收参数,传递数据ViewData,ViewBag,路由,页面布局,wwwroot和客户端库,Razor语法,EnityFrameworkCore与数据库,HttpContext,Request,Response,Session,序列化,文件上传等内容,今天继续讲解ASP.NET Core MVC 中自动映射等相关内容,仅供学习分享使用。

 手动映射

在实际应用中,随着程序复杂度越来越高,分层已经是必然趋势,对象的传递与映射,也变得很频繁。在小项目中,一般采用手动映射赋值,如:将StudentViewModel对象的属性值赋值给Student。手动映射如下所示:
  1. 1 [HttpPost]
  2. 2 public IActionResult Add(StudentViewModel studentViewModel)
  3. 3 {
  4. 4     var student = new Student()
  5. 5     {
  6. 6         Id = studentViewModel.Id,
  7. 7         Name = studentViewModel.Name,
  8. 8         Age = studentViewModel.Age,
  9. 9         Sex = studentViewModel.Sex,
  10. 10     };
  11. 11     studentService.Add(student);
  12. 12     return View();
  13. 13 }
复制代码
手动映射需要逐个属性进行赋值,灵活度高,但也容易出错。如果项目中存在很多需要映射传递的地方,则工作量和复杂度也会随之增加。
自动映射快速入门

自动映射就是由程序自动匹配属性名并进行赋值。步骤如下:
1. 安装自动映射包

首先通过NuGet包管理器安装自动映射第三方库【AutoMapper.Extensions.Microsoft.DependencyInjection】,目前版本为12.0.1,如下所示:

2. 创建自动映射关系

创建自动映射关系类AutomapProfile,并继承自Profile,如下所示:
  1. 1 using AutoMapper;
  2. 2 using DemoCoreMVC.ViewModels;
  3. 3 using DemoCoreMVC.Models;
  4. 4
  5. 5 namespace DemoCoreMVC.Profiles
  6. 6 {
  7. 7     public class AutomapProfile:Profile
  8. 8     {
  9. 9         public AutomapProfile()
  10. 10         {
  11. 11             //创建映射关系
  12. 12             CreateMap<StudentViewModel, Student>();
  13. 13         }
  14. 14     }
  15. 15 }
复制代码
3. 注册自动映射服务

在Program启动文件中,添加自动映射服务,在服务中添加映射关系类,如下所示:
  1. 1 builder.Services.AddAutoMapper(cfg =>
  2. 2 {
  3. 3     cfg.AddProfile<AutomapProfile>();
  4. 4 });
  5. 5 //或者
  6. 6 //builder.Services.AddAutoMapper(typeof(AutomapProfile));
复制代码
4. 注入IMapper接口

在需要使用自动映射服务的地方注入IMapper服务,如控制器中,如下所示:
  1. 1 private readonly IMapper mapper;
  2. 2
  3. 3 public StudentController(IStudentService studentService,IMapper mapper)
  4. 4 {
  5. 5     this.studentService = studentService;
  6. 6     this.mapper = mapper;
  7. 7 }
复制代码
5. 调用映射方法

在需要映射的地方调用IMapper接口的Map方法,如下所示:
  1. 1 [HttpPost]
  2. 2 public IActionResult Add(StudentViewModel studentViewModel)
  3. 3 {
  4. 4     var student =  mapper.Map<StudentViewModel, Student>(studentViewModel);
  5. 5     studentService.Add(student);
  6. 6     return View();
  7. 7 }
复制代码
6. 自动映射示例

经过上述步骤,自动映射已经完成,经过测试如下所示:

多个关系映射文件

在实际应用中,会有很多对象需要映射,通常会根据不同的类型,创建多个关系映射类,则在项目启动注册自动映射服务时,需要加载多个映射类,如下所示:
  1. 1 builder.Services.AddAutoMapper(cfg =>
  2. 2 {
  3. 3     cfg.AddProfile<AutomapProfile>();
  4. 4     cfg.AddProfile<CompanyProfile>();
  5. 5 });
复制代码
也可以通过扫描程序集的方式加载映射文件,可以配置程序集名称,程序会自动扫描继承了Profile类的文件。如下所示:
  1. 1 builder.Services.AddAutoMapper(cfg =>
  2. 2 {
  3. 3     cfg.AddMaps("DemoCoreMVC");
  4. 4 });
复制代码
注意AddMaps参数配置的是程序集名称,而不是命名空间,程序集名称可通过项目属性获取,如下所示:

自动映射匹配

默认情况下,自动映射的数据源和目标的属性,必须要一致,才能进行映射,但是在实际应用中,属性名之间可能会存在差异,如书写格式【Class_Name和ClassName之间的差异】等,如果不加处理的话,默认是无法自动映射成功的。失败示例如下所示:

 在映射时进行配置源的命名格式和目标命名格式,如下所示:
  1. 1 namespace DemoCoreMVC.Profiles
  2. 2 {
  3. 3     public class AutomapProfile:Profile
  4. 4     {
  5. 5         public AutomapProfile()
  6. 6         {
  7. 7             SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
  8. 8             DestinationMemberNamingConvention = new PascalCaseNamingConvention();
  9. 9             //创建映射关系
  10. 10             CreateMap<StudentViewModel, Student>();
  11. 11         }
  12. 12     }
  13. 13 }
复制代码
注意:其中
SourceMemberNamingConvention :源类型成员命名规则Ex: SourceMemberNamingConvention = new LowerUnderscoreNamingConvention(); //下划线命名法DestinationMemberNamingConvention :目标类型成员命名规则Ex: cfg.DestinationMemberNamingConvention = new PascalCaseNamingConvention(); //帕斯卡命名法经过设置源类型和目标类型的命名规则后,则发现已经可以适配成功。如下所示:

 经过测试,以下全局配置命名规则不生效,具体原因不知:
  1. 1 builder.Services.AddAutoMapper(cfg =>
  2. 2 {
  3. 3     cfg.AddProfile<AutomapProfile>();
  4. 4     cfg.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
  5. 5     cfg.DestinationMemberNamingConvention = new PascalCaseNamingConvention();
  6. 6 });
复制代码
以上就是ASP.NET Core MVC从入门到精通之自动映射第一部分内容。旨在抛砖引玉,一起学习,共同进步。

来源:https://www.cnblogs.com/hsiang/archive/2023/06/02/17450526.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具