.NET CORE中使用AutoMapper进行对象映射的方法

这篇文章主要给大家介绍了关于.NET CORE中使用AutoMapper进行对象映射的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用.NET CORE具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
 

简介

AutoMapper uses a fluent configuration API to define an object-object mapping strategy. AutoMapper uses a convention-based matching algorithm to match up source to destination values. AutoMapper is geared towards model projection scenarios to flatten complex object models to DTOs and other simple objects, whose design is better suited for serialization, communication, messaging, or simply an anti-corruption layer between the domain and application layer.

官网:http://automapper.org/

文档:https://automapper.readthedocs.io/en/latest/index.html

GitHub:https://github.com/AutoMapper/AutoMapper/blob/master/docs/index.rst

平台支持:

  • .NET 4.6.1+
  • .NET Standard 2.0+ https://docs.microsoft.com/en-us/dotnet/standard/net-standard

使用

Nuget安装

1
2
AutoMapper 
AutoMapper.Extensions.Microsoft.DependencyInjection //依赖注入AutoMapper,需要下载该包。

在Startup中添加AutoMapper

1
2
3
4
5
6
public void ConfigureServices(IServiceCollection services)
{
 services.AddMvc();
 //添加对AutoMapper的支持
 services.AddAutoMapper();
}

创建AutoMapper映射规则

1
2
3
4
5
6
7
8
9
public class AutoMapperConfigs:Profile
{
 //添加你的实体映射关系.
 public AutoMapperConfigs()
 {
  CreateMap<DBPoundSheet, PoundSheetViewModel>();
  CreateMap<PoundSheetViewModel, DBPoundSheet>();
 }
}

在构造函数中注入你的IMapper

1
2
3
4
5
6
IMapper _mapper;
 
public PoundListController(IMapper mapper)
{
 _mapper = mapper;
}

单个对象转换

1
2
//typeof(model)="PoundSheetViewModel"
DBPoundSheet dBPoundSheet = _mapper.Map<DBPoundSheet>(model);

集合对象转换

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。

 

转 https://www.jb51.net/article/159843.htm

posted @   dreamw  阅读(99)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2021-06-22 mysql安装之初始化报错:mysqld: [ERROR] Found option without preceding group in config file G:\mysql\my.ini at
2021-06-22 .NET面试题大全(C#面试题)2020更新
2021-06-22 mysql 高版本 sql_mode=only_full_group_by 问题解决方法
2021-06-22 Mysql8.0出现this is incompatible with sql_mode=only_full_group_by
2021-06-22 mysql8 设置sql_mode后不能启动
2021-06-22 mysql.ini 配置
2021-06-22 解决Mysql安装之后没有my.ini配置文件问题
点击右上角即可分享
微信分享提示