AutoMapper的介紹與使用(二)

AutoMapper的匹配

? ? ?1,智能匹配

     AutoMapper能夠自動識別和匹配大部分對象屬性:? ??

    • 如果源類和目標類的屬性名稱相同,直接匹配,不區分大小寫
    • 目標類型的CustomerName可以匹配源類型的Customer.Name
    • 目標類型的Total可以匹配源類型的GetTotal()方法

? ? 2,自定義匹配

    Mapper.CreateMap<CalendarEvent, CalendarEventForm>() ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//屬性匹配,匹配源類中WorkEvent.Date到EventDate

    .ForMember(dest => dest.EventDate, opt => opt.MapFrom(src => src.WorkEvent.Date))

    .ForMember(dest => dest.SomeValue, opt => opt.Ignore()) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //忽略目標類中的屬性

    .ForMember(dest => dest.TotalAmount, opt => opt.MapFrom(src => src.TotalAmount ?? 0)) ?//復雜的匹配

    .ForMember(dest => dest.OrderDate, opt => opt.UserValue<DateTime>(DateTime.Now)); ? ? ?//固定值匹配

直接匹配

源類的屬性名稱和目標類的屬性名稱相同(不區分大小寫),直接匹配,Mapper.CreateMap<source,dest>();無需做其他處理,此處不再細述

Flattening

?將一個復雜的對象模型拉伸為,或者扁平化為一個簡單的對象模型,如下面這個復雜的對象模型:

        public class Order{private readonly IList<OrderLineItem> _orderLineItems = new List<OrderLineItem>();public Customer Customer { get; set; }public OrderLineItem[] GetOrderLineItems(){return _orderLineItems.ToArray();}public void AddOrderLineItem(Product product, int quantity){_orderLineItems.Add(new OrderLineItem(product, quantity));}public decimal GetTotal(){return _orderLineItems.Sum(li => li.GetTotal());}}public class Product{public decimal Price { get; set; }public string Name { get; set; }}public class OrderLineItem{public OrderLineItem(Product product, int quantity){Product = product;Quantity = quantity;}public Product Product { get; private set; }public int Quantity { get; private set; }public decimal GetTotal(){return Quantity * Product.Price;}}public class Customer{public string Name { get; set; }}

我們要把這一復雜的對象簡化為OrderDTO,只包含某一場景所需要的數據:

        public class OrderDto{public string CustomerName { get; set; }public decimal Total { get; set; }}

運用AutoMapper轉換:

            public void Example(){// Complex modelvar customer = new Customer{Name = "George Costanza"};var order = new Order{Customer = customer};var bosco = new Product{Name = "Bosco",Price = 4.99m};order.AddOrderLineItem(bosco, 15);// Configure AutoMappervar config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDto>());// Perform mappingvar mapper = config.CreateMapper();OrderDto dto = mapper.Map<Order, OrderDto>(order);dto.CustomerName.ShouldEqual("George Costanza");dto.Total.ShouldEqual(74.85m);}

可以看到只要設置下Order和OrderDto之間的類型映射就可以了,我們看OrderDto中的CustomerName和Total屬性在領域模型Order中并沒有與之相對性,AutoMapper在做解析的時候會按照PascalCase(帕斯卡命名法),CustomerName其實是由Customer+Name 得來的,是AutoMapper的一種映射規則;而Total是因為在Order中有GetTotal()方法,AutoMapper會解析“Get”之后的單詞,所以會與Total對應。在編寫代碼過程中可以運用這種規則來定義名稱實現自動轉換。

Projection

Projection可以理解為與Flattening相反,Projection是將源對象映射到一個不完全與源對象匹配的目標對象,需要制定自定義成員,如下面的源對象:

        public class CalendarEvent{public DateTime EventDate { get; set; }public string Title { get; set; }}

目標對象:

        public class CalendarEventForm{public DateTime EventDate { get; set; }public int EventHour { get; set; }public int EventMinute { get; set; }public string Title { get; set; }}

AutoMapper配置轉換代碼:

            public void Example(){// Modelvar calendarEvent = new CalendarEvent{EventDate = new DateTime(2008, 12, 15, 20, 30, 0),Title = "Company Holiday Party"};var config = new MapperConfiguration(cfg =>{// Configure AutoMappercfg.CreateMap<CalendarEvent, CalendarEventForm>().ForMember(dest => dest.EventDate, opt => opt.MapFrom(src => src.EventDate.Date)).ForMember(dest => dest.EventHour, opt => opt.MapFrom(src => src.EventDate.Hour)).ForMember(dest => dest.EventMinute, opt => opt.MapFrom(src => src.EventDate.Minute));});// Perform mappingvar mapper = config.CreateMapper();CalendarEventForm form = mapper.Map<CalendarEvent, CalendarEventForm>(calendarEvent);form.EventDate.ShouldEqual(new DateTime(2008, 12, 15));form.EventHour.ShouldEqual(20);form.EventMinute.ShouldEqual(30);form.Title.ShouldEqual("Company Holiday Party");}

?Configuration Validation

在進行對象映射的時候,有可能會出現屬性名稱或者自定義匹配規則不正確而又沒有發現的情況,在程序執行時就報錯,因此,AutoMapper提供的AssertConfigurationIsValid()方法來驗證結構映射是否正確。

?config.AssertConfigurationIsValid();如果映射錯誤,會報“AutoMapperConfigurationException”異常錯誤,就可以進行調試修改了

?Lists and Array

AutoMapper支持的源集合類型包括:

  • IEnumerable
  • IEnumerable<T>
  • ICollection
  • ICollection<T>
  • IList
  • IList<T>
  • List<T>
  • Arrays

有一種情況是,在使用集合類型類型的時候,類型之間存在繼承關系,例如下面我們需要轉換的類型:

            //源對象public class ParentSource{public int Value1 { get; set; }}public class ChildSource : ParentSource{public int Value2 { get; set; }}//目標對象public class ParentDestination{public int Value1 { get; set; }}public class ChildDestination : ParentDestination{public int Value2 { get; set; }}

AutoMapper需要孩子映射的顯式配置,AutoMapper配置轉換代碼:

                var config = new MapperConfiguration(cfg =>{cfg.CreateMap<ParentSource, ParentDestination>().Include<ChildSource, ChildDestination>();cfg.CreateMap<ChildSource, ChildDestination>();});var sources = new[]{new ParentSource(),new ChildSource(),new ParentSource()};var destinations = config.CreateMapper().Map<ParentSource[], ParentDestination[]>(sources);destinations[0].ShouldBeType<ParentDestination>();destinations[1].ShouldBeType<ChildDestination>();destinations[2].ShouldBeType<ParentDestination>();

注意在Initialize初始化CreateMap進行類型映射配置的時候有個Include泛型方法,簽名為:“Include this configuration in derived types' maps”,大致意思為包含派生類型中配置,ChildSource是ParentSource的派生類,ChildDestination是ParentDestination的派生類,cfg.CreateMap<ParentSource, ParentDestination>().Include<ChildSource, ChildDestination>(); 這段代碼是說明ParentSource和ChildSource之間存在的關系,并且要要顯示的配置。

?Nested mappings

嵌套對象映射,例如下面的對象:

       public class OuterSource{public int Value { get; set; }public InnerSource Inner { get; set; }}public class InnerSource{public int OtherValue { get; set; }}//目標對象public class OuterDest{public int Value { get; set; }public InnerDest Inner { get; set; }}public class InnerDest{public int OtherValue { get; set; }}

AutoMapper配置轉換代碼:

                var config = new MapperConfiguration(cfg =>{cfg.CreateMap<OuterSource, OuterDest>();cfg.CreateMap<InnerSource, InnerDest>();});config.AssertConfigurationIsValid();var source = new OuterSource{Value = 5,Inner = new InnerSource {OtherValue = 15}};var dest = config.CreateMapper().Map<OuterSource, OuterDest>(source);dest.Value.ShouldEqual(5);dest.Inner.ShouldNotBeNull();dest.Inner.OtherValue.ShouldEqual(15);

對于嵌套映射,只要指定下類型映射關系和嵌套類型映射關系就可以了,也就是這段代碼:“Mapper.CreateMap<InnerSource, InnerDest>();” 其實我們在驗證類型映射的時候加上Mapper.AssertConfigurationIsValid(); 這段代碼看是不是拋出“AutoMapperMappingException”異常來判斷類型映射是否正確。

參考資料

  • https://github.com/AutoMapper/AutoMapper/wiki
  • http://www.cnblogs.com/farb/p/AutoMapperContent.html

關于AutoMapper,陸續更新中...

?

轉載于:https://www.cnblogs.com/yanyangxue2016/p/6229539.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/394286.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394286.shtml
英文地址,請注明出處:http://en.pswp.cn/news/394286.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

站長快訊 WordPress跨站攻擊漏洞修補

WordPress中發現一些漏洞&#xff0c;攻擊者利用該漏洞可以發起跨站腳本攻擊&#xff0c;繞過WordPress安全性限制&#xff0c;獲取較為敏感的修訂歷史記錄的信息&#xff0c;或者綁架站點以用于DDoS攻擊。 CVE ID CVE-2015-8834 CVE-2016-5832 CVE-2016-5834 CVE-2016-5835 C…

暢通無阻的公式:乘員組從幾乎破產變成了吸引500萬游客的方式

How could you go from almost no traction and running out of money, to getting millions of visitors to your website?您怎么能從幾乎沒有牽引力和資金用盡的角度&#xff0c;如何吸引數百萬的網站訪問者&#xff1f; You could do like Crew accidentally did with Uns…

leetcode1302. 層數最深葉子節點的和(深度優先搜索)

給你一棵二叉樹&#xff0c;請你返回層數最深的葉子節點的和。 代碼 class Solution {int[] depthnew int[]{Integer.MIN_VALUE,0};//記錄最深層數和對應的和public int deepestLeavesSum(TreeNode root) {if(rootnull) return 0;deep(root,0);return depth[1];}public void d…

Python筆記 【無序】 【五】

描述符 將某種特殊類型的類【只要實現了以下或其中一個】的實例指派給另一個類的屬性 1.__get__(self,instance,owner)//訪問屬性&#xff0c;返回屬性的值 2.__set__(self,instance,value)//將在屬性分配【即賦值】中調用&#xff0c;不返回任何內容 3.__delete__&#xff08;…

化工圖紙中LISP_化工設備廠參展模型設計制作

最近這個案子是受某化工設備企業委托做四套設備模型 用來參加展會在模型制作過程中&#xff0c;這類案例經常遇到。但是客戶所提供的CAD圖紙&#xff0c;往往是實物尺寸在進行縮放的過程中常會造成過薄和過于精細的情況出現眼下技術小哥就遇到這類情況讓我們先看看客戶提供的C…

社交大佬們的數據“大”在哪里?

文章講的是社交大佬們的數據“大”在哪里&#xff0c;“別說忙&#xff0c;沒工夫看書&#xff0c;你那刷FB/朋友圈的工夫騰出來&#xff0c;保證每周啃下一本”&#xff0c;小編身邊總充斥著這樣的“訓話”。 額&#xff0c;奈何我每天的工作離不開從社交媒體中獲取信息&#…

微信支付JsAPI

https://pay.weixin.qq.com/wiki/doc/api/download/WxpayAPI_php_v3.zip 下載獲取微信支付demo壓縮包打開壓縮包&#xff0c;并將其中 WxpayAPI_php_v3\example下的 jsapi.php log.php WxPay.JsApiPay.php WxPay.MicroPay.php WxPay.NativePay.php 解壓縮到根目錄 tellingtent/…

mysql 多數據源訪問_通過Spring Boot配置動態數據源訪問多個數據庫的實現代碼

之前寫過一篇博客《SpringMybatisMysql搭建分布式數據庫訪問框架》描述如何通過SpringMybatis配置動態數據源訪問多個數據庫。但是之前的方案有一些限制(原博客中也描述了)&#xff1a;只適用于數據庫數量不多且固定的情況。針對數據庫動態增加的情況無能為力。下面講的方案能支…

我如何將Google I / O 2018的興奮帶給尼日利亞沃里的115個人

Google Developer Group Warri的第一個I / O擴展事件的故事 (A tale of Google Developer Group Warri’s first I/O Extended event) Google I/O is one of the largest developer festivals in the tech ecosystem. I am the lead organizer for the Google Developer Group …

菜鳥postman接口測試_postman 接口測試(轉)

本文轉載自testerhome&#xff1b;作者&#xff1a;xinxi1990 &#xff1b;原文鏈接&#xff1a;https://testerhome.com/topics/18719&#xff1b;轉載以分享知識為目的&#xff0c;著作權歸原作者所有&#xff0c;如有侵權&#xff0c;請聯系刪除。postman使用創建用例集啟動…

求絕對值最小的數

題目 有一個升序排列的數組&#xff0c;數組中可能有正數&#xff0c;負數或0. 求數組中元素的絕對值最小的數. 例如 數組{-10&#xff0c; 05&#xff0c; 02 &#xff0c;7&#xff0c;15&#xff0c;50} 絕對值最小的是-2 解答 #include <bits/stdc.h> using namespac…

leetcode面試題 04.02. 最小高度樹(深度優先搜索)

給定一個有序整數數組&#xff0c;元素各不相同且按升序排列&#xff0c;編寫一個算法&#xff0c;創建一棵高度最小的二叉搜索樹。 public TreeNode sortedArrayToBST(int[] nums) {if(nums.length0) return null;return BST(nums,0,nums.length-1);}public TreeNode BST(int[…

IT團隊如何贏得尊重?

本文講的是IT團隊如何贏得尊重,在傳統觀念中&#xff0c;作為企業的IT人&#xff0c;似乎都有一種揮之不去的消極情緒&#xff1a;能夠為企業帶來直接利益的業務部門才是企業核心&#xff0c;而作為技術支撐的IT部門&#xff0c;則是作為附屬而存在。 我們經常也會聽到一些企業…

mysql 官方鏡像_運行官方mysql 鏡像

//目前最新的為mysql 8sudo docker run -itd --restart unless-stopped --nethost --name mysql -p3306:3306 -e MYSQL_ROOT_PASSWORDroot mysqlmysql 官方docker 需要重新設置密碼&#xff0c;否則無法遠程連接step1 : docker exec -it [容器id] /bin/bashstep2 : 登陸mysql &…

我如何使用React,Redux-Saga和Styled Components構建NBA球員資料獲取器

by Jonathan Puc喬納森普克(Jonathan Puc) 我如何使用React&#xff0c;Redux-Saga和Styled Components構建NBA球員資料獲取器 (How I built an NBA player profile fetcher with React, Redux-Saga, and Styled Components) Hello, all! It’s been a while since I built so…

vb 數組屬性_VB中菜單編輯器的使用講解及實際應用

大家好&#xff0c;今天我們共同來學習VB中菜單方面的知識。VB中菜單的基本作用有兩個&#xff1a;1、提供人機對話的界面&#xff0c;以便讓使用者選擇應用系統的各種功能&#xff1b;2、管理應用系統&#xff0c;控制各種功能模塊的運行。在實際應用中&#xff0c;菜單可分為…

《JAVA程序設計》_第七周學習總結

一、學習內容 1.String類——8,1知識 Java專門提供了用來處理字符序列的String類。String類在java.lang包中&#xff0c;由于java.lang包中的類被默認引入&#xff0c;因此程序可以直接使用String類。需要注意的是Java把String類聲明為final類&#xff0c;因此用戶不能擴展Stri…

leetcode109. 有序鏈表轉換二叉搜索樹(深度優先搜索/快慢指針)

給定一個單鏈表&#xff0c;其中的元素按升序排序&#xff0c;將其轉換為高度平衡的二叉搜索樹。 本題中&#xff0c;一個高度平衡二叉樹是指一個二叉樹每個節點 的左右兩個子樹的高度差的絕對值不超過 1。 解題思路 先將鏈表轉換成數組&#xff0c;再構造二叉搜索樹 代碼 …

NeHe OpenGL教程 第三十七課:卡通映射

轉自【翻譯】NeHe OpenGL 教程 前言 聲明&#xff0c;此 NeHe OpenGL教程系列文章由51博客yarin翻譯&#xff08;2010-08-19&#xff09;&#xff0c;本博客為轉載并稍加整理與修改。對NeHe的OpenGL管線教程的編寫&#xff0c;以及yarn的翻譯整理表示感謝。 NeHe OpenGL第三十七…

SDN交換機在云計算網絡中的應用場景

SDN的技術已經發展了好幾年了&#xff0c;而云計算的歷史更長&#xff0c;兩者的結合更是作為SDN的一個殺手級應用在近兩年炒得火熱&#xff0c;一些知名咨詢公司的關于SDN逐年增加的市場份額的論斷&#xff0c;也主要是指SDN在云計算網絡中的應用。 關于SDN在云計算網絡中的應…