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

集合對象轉換


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM