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

网络编程 2021-07-04 22:41www.168986.cn编程入门
这篇文章主要给大家介绍了关于.NET CORE中使用AutoMapper进行对象映射的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用.NET CORE具有一定的参考学习价值,需要的朋友们狼蚁网站SEO优化来一起学习学习吧

简介

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 plex object models to DTOs and other simple objects, whose design is better suited for serialization, munication, messaging, or simply an anti-corruption layer between the domain and application layer.

官网http://automapper./

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

GitHubhttps://github./AutoMapper/AutoMapper/blob/master/docs/index.rst

平台支持

  • .NET 4.6.1+
  • .NET Standard 2.0+ https://docs.microsoft./en-us/dot/standard/-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);

集合对象转换

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

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by