.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安裝

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

集合對象轉換

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對神馬文庫的支持。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章