.NET CORE中使用AutoMapper进行对象映射的方法
简介
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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享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配置文件问题