写在前面

知道AutoMapper很久了,但是一直没有用,最近刚好有个场景需要就用了,果然是利器。看了git上的wiki,发现内容其实wiki上写的很全面了,深入的暂时还没挖掘到。不过和群里的朋友交流了下,觉得充当下搬运工,小小的翻译下还是挺好的,小弟不才,希望看客大牛们轻拍砖。

什么是AutoMapper?

 AutoMapper是一个完善的Mapping工具,所谓Mapping即数据对象转换,借用群里朋友的话是多用于领域对象和DTO对象的Mapping或者是SqlDataReader的Mapping。

 Git主页:https://github.com/AutoMapper/AutoMapper

 Wiki主页:https://github.com/AutoMapper/AutoMapper/wiki

简单的例子

场景是这样的在订单业务里,有Order、Customer、Product三个对象如下,其中Product被包含在OrderLinItem对象中:

 1 public class Order
 2 {
 3   private readonly IList<OrderLineItem> _orderLineItems = new List<OrderLineItem>();
 4 
 5   public Customer Customer { get; set; }
 6 
 7   public OrderLineItem[] GetOrderLineItems()
 8   {
 9     return _orderLineItems.ToArray();
10   }
11 
12   public void AddOrderLineItem(Product product, int quantity)
13   {
14     _orderLineItems.Add(new OrderLineItem(product, quantity));
15   }
16 
17   public decimal GetTotal()
18   {
19     return _orderLineItems.Sum(li => li.GetTotal());
20   }
21 }
22 }
23 
24 public class OrderLineItem
25 {
26   public OrderLineItem(Product product, int quantity)
27   {
28     Product = product;
29     Quantity = quantity;
30   }
31 
32   public Product Product { get; private set; }
33   public int Quantity { get; private set;}
34 
35   public decimal GetTotal()
36   {
37     return Quantity*Product.Price;
38   }
39 }
40 
41 public class Customer
42 {
43   public string Name { get; set; }
44 }
45 
46 public class Product
47 {
48   public decimal Price { get; set; }
49   public string Name { get; set; }
50 }
View Code

相关文章: