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

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了.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安装

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);

集合对象转换

总结

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

脚本宝典总结

以上是脚本宝典为你收集整理的.NET CORE中使用AutoMapper进行对象映射的方法全部内容,希望文章能够帮你解决.NET CORE中使用AutoMapper进行对象映射的方法所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。