欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-10 08:28:16
简介 automapper uses a fluent configuration api to define an object-object mapping st...

简介

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安装

automapper  
automapper.extensions.microsoft.dependencyinjection //依赖注入automapper,需要下载该包。

在startup中添加automapper

public void configureservices(iservicecollection services)
{
 services.addmvc();
 //添加对automapper的支持
 services.addautomapper();
}

创建automapper映射规则

public class automapperconfigs:profile
{
 //添加你的实体映射关系.
 public automapperconfigs()
 {
  createmap<dbpoundsheet, poundsheetviewmodel>();
  createmap<poundsheetviewmodel, dbpoundsheet>();
 }
}

在构造函数中注入你的imapper

imapper _mapper;

public poundlistcontroller(imapper mapper)
{
 _mapper = mapper;
}

单个对象转换

//typeof(model)="poundsheetviewmodel"
dbpoundsheet dbpoundsheet = _mapper.map<dbpoundsheet>(model);

集合对象转换

总结

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