1. 程式人生 > >.NET CORE 中使用AutoMapper進行物件對映

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

集合物件轉換