官方项目下载:
http://automapper.codeplex.com/
博文
http://www.iteye.com/blogs/tag/AutoMapper
图解:
第一步:创建映射Map:AutoMapperBootStrapper.cs
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using Agathas.Storefront.Infrastructure.Helpers; 6 using Agathas.Storefront.Model; 7 using Agathas.Storefront.Model.Basket; 8 using Agathas.Storefront.Model.Categories; 9 using Agathas.Storefront.Model.Customers; 10 using Agathas.Storefront.Model.Orders; 11 using Agathas.Storefront.Model.Orders.States; 12 using Agathas.Storefront.Model.Products; 13 using Agathas.Storefront.Model.Shipping; 14 using Agathas.Storefront.Services.ViewModels; 15 using AutoMapper; 16 17 namespace Agathas.Storefront.Services 18 { 19 public class AutoMapperBootStrapper 20 { 21 public static void ConfigureAutoMapper() 22 { 23 // Product Title 24 Mapper.CreateMap<ProductTitle, ProductSummaryView>(); 25 Mapper.CreateMap<ProductTitle, ProductView>(); 26 Mapper.CreateMap<Product, ProductSummaryView>(); 27 Mapper.CreateMap<Product, ProductSizeOption>(); 28 29 // Category 30 Mapper.CreateMap<Category, CategoryView>(); 31 32 // IProductAttribute 33 Mapper.CreateMap<IProductAttribute, Refinement>(); 34 35 // Basket 36 Mapper.CreateMap<DeliveryOption, DeliveryOptionView>(); 37 Mapper.CreateMap<BasketItem, BasketItemView>(); 38 Mapper.CreateMap<Basket, BasketView>(); 39 40 // Customer 41 Mapper.CreateMap<Customer, CustomerView>(); 42 Mapper.CreateMap<DeliveryAddress, DeliveryAddressView>(); 43 44 // Orders 45 Mapper.CreateMap<Order, OrderView>(); 46 Mapper.CreateMap<OrderItem, OrderItemView>(); 47 Mapper.CreateMap<Address, DeliveryAddressView>(); 48 Mapper.CreateMap<Order, OrderSummaryView>() 49 .ForMember(o => o.IsSubmitted, 50 ov => ov.ResolveUsing<OrderStatusResolver>()); 51 52 53 // Global Money Formatter 54 Mapper.AddFormatter<MoneyFormatter>(); 55 56 } 57 } 58 59 public class OrderStatusResolver : ValueResolver<Order, bool> 60 { 61 protected override bool ResolveCore(Order source) 62 { 63 if (source.Status == OrderStatus.Submitted) 64 { 65 return true; 66 } 67 else 68 { 69 return false; 70 } 71 } 72 } 73 74 75 public class MoneyFormatter : IValueFormatter 76 { 77 public string FormatValue(ResolutionContext context) 78 { 79 if (context.SourceValue is decimal) 80 { 81 decimal money = (decimal)context.SourceValue; 82 83 return money.FormatMoney(); 84 } 85 86 return context.SourceValue.ToString(); 87 } 88 } 89 90 }
这里是两个要创建映射的实体类
Order.cs
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using Agathas.Storefront.Infrastructure.Domain; 6 using Agathas.Storefront.Model.Customers; 7 using Agathas.Storefront.Model.Orders.States; 8 using Agathas.Storefront.Model.Products; 9 using Agathas.Storefront.Model.Shipping; 10 11 namespace Agathas.Storefront.Model.Orders 12 { 13 public class Order : EntityBase<int>, IAggregateRoot 14 { 15 private IList<OrderItem> _items; 16 private DateTime _created; 17 private Payment _payment; 18 private IOrderState _state; 19 20 public Order() 21 { 22 _created = DateTime.Now; 23 _items = new List<OrderItem>(); 24 _state = OrderStates.Open; 25 } 26 27 public DateTime Created 28 { 29 get { return _created; } 30 } 31 32 public decimal ShippingCharge { get; set; } 33 34 public ShippingService ShippingService { get; set; } 35 36 public decimal ItemTotal() 37 { 38 return Items.Sum(i => i.LineTotal()); 39 } 40 41 public decimal Total() 42 { 43 return Items.Sum(i => i.LineTotal()) + ShippingCharge; 44 } 45 46 public Payment Payment 47 { 48 get { return _payment; } 49 } 50 51 public void SetPayment(Payment payment) 52 { 53 if (OrderHasBeenPaidFor()) 54 throw new OrderAlreadyPaidForException( 55 GetDetailsOnExisitingPayment()); 56 57 if (OrderTotalMatches(payment)) 58 _payment = payment; 59 else 60 throw new PaymentAmountDoesNotEqualOrderTotalException( 61 GetDetailsOnIssueWith(payment)); 62 63 _state.Submit(this); 64 } 65 66 private string GetDetailsOnExisitingPayment() 67 { 68 return String.Format("Order has already been paid for. " + 69 "{0} was paid on {1}. Payment token '{2}'", 70 Payment.Amount, Payment.DatePaid, 71 Payment.TransactionId); 72 } 73 74 private string GetDetailsOnIssueWith(Payment payment) 75 { 76 return String.Format("Payment amount is invalid. " + 77 "Order total is {0} but payment for {1}." + 78 " Payment token '{2}'", 79 this.Total(), payment.Amount, payment.TransactionId); 80 } 81 82 public bool OrderHasBeenPaidFor() 83 { 84 return Payment != null && OrderTotalMatches(Payment); 85 } 86 87 private bool OrderTotalMatches(Payment payment) 88 { 89 return Total() == payment.Amount; 90 } 91 92 public Customer Customer { get; set; } 93 94 public Address DeliveryAddress { get; set; } 95 96 public IEnumerable<OrderItem> Items 97 { 98 get { return _items; } 99 } 100 101 public OrderStatus Status 102 { 103 get { return _state.Status; } 104 } 105 106 public void AddItem(Product product, int qty) 107 { 108 if (_state.CanAddProduct()) 109 { 110 if (!OrderContains(product)) 111 _items.Add(OrderItemFactory.CreateItemFor(product, this, qty)); 112 } 113 else 114 throw new CannotAmendOrderException(String.Format( 115 "You cannot add an item to an order with the status of '{0}'.", 116 Status.ToString())); 117 } 118 119 private bool OrderContains(Product product) 120 { 121 return _items.Any(i => i.Contains(product)); 122 } 123 124 protected override void Validate() 125 { 126 if (Created == DateTime.MinValue) 127 base.AddBrokenRule(OrderBusinessRules.CreatedDateRequired); 128 129 if (Customer == null) 130 base.AddBrokenRule(OrderBusinessRules.CustomerRequired); 131 132 if (DeliveryAddress == null) 133 base.AddBrokenRule(OrderBusinessRules.DeliveryAddressRequired); 134 135 if (Items == null || Items.Count() == 0) 136 base.AddBrokenRule(OrderBusinessRules.ItemsRequired); 137 else 138 { 139 if (Items.Any(i => i.GetBrokenRules().Count() > 0)) 140 { 141 foreach (OrderItem item in Items.Where(i => i.GetBrokenRules().Count() > 0)) 142 { 143 foreach (BusinessRule businessRule in item.GetBrokenRules()) 144 { 145 base.AddBrokenRule(businessRule); 146 } 147 } 148 } 149 } 150 151 if (ShippingService == null) 152 base.AddBrokenRule(OrderBusinessRules.ShippingServiceRequired); 153 154 } 155 156 internal void SetStateTo(IOrderState state) 157 { 158 this._state = state; 159 } 160 161 public override string ToString() 162 { 163 StringBuilder orderInfo = new StringBuilder(); 164 165 foreach (OrderItem item in _items) 166 { 167 orderInfo.AppendLine(String.Format("{0} of {1} ", 168 item.Qty, item.Product.Name)); 169 } 170 171 orderInfo.AppendLine(String.Format("Shipping: {0}", this.ShippingCharge)); 172 orderInfo.AppendLine(String.Format("Total: {0}", this.Total())); 173 174 return orderInfo.ToString(); 175 176 } 177 } 178 179 }
OrderSummaryView.cs
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace Agathas.Storefront.Services.ViewModels 7 { 8 public class OrderSummaryView 9 { 10 public int Id { get; set; } 11 public DateTime Created { get; set; } 12 public bool IsSubmitted { get; set; } 13 } 14 15 }
第二步:启用配置:
protected void Application_Start() { Services.AutoMapperBootStrapper.ConfigureAutoMapper();
第三步:使用:OrderMapper.cs
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using Agathas.Storefront.Model.Orders; 6 using Agathas.Storefront.Services.ViewModels; 7 using AutoMapper; 8 9 namespace Agathas.Storefront.Services.Mapping 10 { 11 public static class OrderMapper 12 { 13 public static OrderView ConvertToOrderView(this Order order) 14 { 15 return Mapper.Map<Order, OrderView>(order); 16 } 17 18 public static IEnumerable<OrderSummaryView> ConvertToOrderSummaryViews( 19 this IEnumerable<Order> orders) 20 { 21 return Mapper.Map<IEnumerable<Order>, IEnumerable<OrderSummaryView>>(orders); 22 } 23 } 24 25 }
在需要两个类型转换的地方调用:
1 Order order = new 。。。; 2 OrderView orderView = order.ConvertToOrderView();
1 OrderSummaryViews orderSummaryViews = new .....; 2 IEnumerable<OrderSummaryView> Orders = orderSummaryViews.ConvertToOrderSummaryViews()