.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.
官網(wǎng):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(); }
創(chuàng)建AutoMapper映射規(guī)則
public class AutoMapperConfigs:Profile { //添加你的實體映射關(guān)系. public AutoMapperConfigs() { CreateMap<DBPoundSheet, PoundSheetViewModel>(); CreateMap<PoundSheetViewModel, DBPoundSheet>(); } }
在構(gòu)造函數(shù)中注入你的IMapper
IMapper _mapper; public PoundListController(IMapper mapper) { _mapper = mapper; }
單個對象轉(zhuǎn)換
//typeof(model)="PoundSheetViewModel" DBPoundSheet dBPoundSheet = _mapper.Map<DBPoundSheet>(model);
集合對象轉(zhuǎn)換
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。
相關(guān)文章
asp.net實現(xiàn)DataList與Repeater嵌套綁定的方法
這篇文章主要介紹了asp.net實現(xiàn)DataList與Repeater嵌套綁定的方法,結(jié)合實例形式分析了DataList與Repeater的步驟與相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2016-04-04asp.net 網(wǎng)絡(luò)硬盤實現(xiàn)分析
隨著網(wǎng)絡(luò)技術(shù)的日益普及和信息化建設(shè)的重視,網(wǎng)絡(luò)硬盤作為一種新型安全的網(wǎng)絡(luò)存儲系統(tǒng),已越來越受到人們的重視和喜歡。2011-02-02解析WPF綁定層次結(jié)構(gòu)數(shù)據(jù)的應(yīng)用詳解
本文講述WPF中單層次數(shù)據(jù)和多層次數(shù)據(jù)的綁定方法,主要闡述數(shù)據(jù)綁定的顯示層面,其中涉及了ListBox和Treeview控件。并說明它們之間的差異2013-05-05asp.net repeater實現(xiàn)批量刪除時注冊多選框id到客戶端
repeater批量刪除時注冊多選框id到客戶端的實現(xiàn)代碼2008-11-11