【AutoMapper】实体类间自动实现映射关系,及其转换。

官方项目下载:

http://automapper.codeplex.com/

博文

http://www.iteye.com/blogs/tag/AutoMapper

图解:

【AutoMapper】实体类间自动实现映射关系,及其转换。

第一步:创建映射Map:AutoMapperBootStrapper.cs

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Agathas.Storefront.Infrastructure.Helpers;
using Agathas.Storefront.Model;
using Agathas.Storefront.Model.Basket;
using Agathas.Storefront.Model.Categories;
using Agathas.Storefront.Model.Customers;
using Agathas.Storefront.Model.Orders;
using Agathas.Storefront.Model.Orders.States;
using Agathas.Storefront.Model.Products;
using Agathas.Storefront.Model.Shipping;
using Agathas.Storefront.Services.ViewModels;
using AutoMapper; namespace Agathas.Storefront.Services
{
public class AutoMapperBootStrapper
{
public static void ConfigureAutoMapper()
{
// Product Title
Mapper.CreateMap<ProductTitle, ProductSummaryView>();
Mapper.CreateMap<ProductTitle, ProductView>();
Mapper.CreateMap<Product, ProductSummaryView>();
Mapper.CreateMap<Product, ProductSizeOption>(); // Category
Mapper.CreateMap<Category, CategoryView>(); // IProductAttribute
Mapper.CreateMap<IProductAttribute, Refinement>(); // Basket
Mapper.CreateMap<DeliveryOption, DeliveryOptionView>();
Mapper.CreateMap<BasketItem, BasketItemView>();
Mapper.CreateMap<Basket, BasketView>(); // Customer
Mapper.CreateMap<Customer, CustomerView>();
Mapper.CreateMap<DeliveryAddress, DeliveryAddressView>(); // Orders
Mapper.CreateMap<Order, OrderView>();
Mapper.CreateMap<OrderItem, OrderItemView>();
Mapper.CreateMap<Address, DeliveryAddressView>();
Mapper.CreateMap<Order, OrderSummaryView>()
.ForMember(o => o.IsSubmitted,
ov => ov.ResolveUsing<OrderStatusResolver>()); // Global Money Formatter
Mapper.AddFormatter<MoneyFormatter>(); }
} public class OrderStatusResolver : ValueResolver<Order, bool>
{
protected override bool ResolveCore(Order source)
{
if (source.Status == OrderStatus.Submitted)
{
return true;
}
else
{
return false;
}
}
} public class MoneyFormatter : IValueFormatter
{
public string FormatValue(ResolutionContext context)
{
if (context.SourceValue is decimal)
{
decimal money = (decimal)context.SourceValue; return money.FormatMoney();
} return context.SourceValue.ToString();
}
} }

这里是两个要创建映射的实体类

Order.cs

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Agathas.Storefront.Infrastructure.Domain;
using Agathas.Storefront.Model.Customers;
using Agathas.Storefront.Model.Orders.States;
using Agathas.Storefront.Model.Products;
using Agathas.Storefront.Model.Shipping; namespace Agathas.Storefront.Model.Orders
{
public class Order : EntityBase<int>, IAggregateRoot
{
private IList<OrderItem> _items;
private DateTime _created;
private Payment _payment;
private IOrderState _state; public Order()
{
_created = DateTime.Now;
_items = new List<OrderItem>();
_state = OrderStates.Open;
} public DateTime Created
{
get { return _created; }
} public decimal ShippingCharge { get; set; } public ShippingService ShippingService { get; set; } public decimal ItemTotal()
{
return Items.Sum(i => i.LineTotal());
} public decimal Total()
{
return Items.Sum(i => i.LineTotal()) + ShippingCharge;
} public Payment Payment
{
get { return _payment; }
} public void SetPayment(Payment payment)
{
if (OrderHasBeenPaidFor())
throw new OrderAlreadyPaidForException(
GetDetailsOnExisitingPayment()); if (OrderTotalMatches(payment))
_payment = payment;
else
throw new PaymentAmountDoesNotEqualOrderTotalException(
GetDetailsOnIssueWith(payment)); _state.Submit(this);
} private string GetDetailsOnExisitingPayment()
{
return String.Format("Order has already been paid for. " +
"{0} was paid on {1}. Payment token '{2}'",
Payment.Amount, Payment.DatePaid,
Payment.TransactionId);
} private string GetDetailsOnIssueWith(Payment payment)
{
return String.Format("Payment amount is invalid. " +
"Order total is {0} but payment for {1}." +
" Payment token '{2}'",
this.Total(), payment.Amount, payment.TransactionId);
} public bool OrderHasBeenPaidFor()
{
return Payment != null && OrderTotalMatches(Payment);
} private bool OrderTotalMatches(Payment payment)
{
return Total() == payment.Amount;
} public Customer Customer { get; set; } public Address DeliveryAddress { get; set; } public IEnumerable<OrderItem> Items
{
get { return _items; }
} public OrderStatus Status
{
get { return _state.Status; }
} public void AddItem(Product product, int qty)
{
if (_state.CanAddProduct())
{
if (!OrderContains(product))
_items.Add(OrderItemFactory.CreateItemFor(product, this, qty));
}
else
throw new CannotAmendOrderException(String.Format(
"You cannot add an item to an order with the status of '{0}'.",
Status.ToString()));
} private bool OrderContains(Product product)
{
return _items.Any(i => i.Contains(product));
} protected override void Validate()
{
if (Created == DateTime.MinValue)
base.AddBrokenRule(OrderBusinessRules.CreatedDateRequired); if (Customer == null)
base.AddBrokenRule(OrderBusinessRules.CustomerRequired); if (DeliveryAddress == null)
base.AddBrokenRule(OrderBusinessRules.DeliveryAddressRequired); if (Items == null || Items.Count() == )
base.AddBrokenRule(OrderBusinessRules.ItemsRequired);
else
{
if (Items.Any(i => i.GetBrokenRules().Count() > ))
{
foreach (OrderItem item in Items.Where(i => i.GetBrokenRules().Count() > ))
{
foreach (BusinessRule businessRule in item.GetBrokenRules())
{
base.AddBrokenRule(businessRule);
}
}
}
} if (ShippingService == null)
base.AddBrokenRule(OrderBusinessRules.ShippingServiceRequired); } internal void SetStateTo(IOrderState state)
{
this._state = state;
} public override string ToString()
{
StringBuilder orderInfo = new StringBuilder(); foreach (OrderItem item in _items)
{
orderInfo.AppendLine(String.Format("{0} of {1} ",
item.Qty, item.Product.Name));
} orderInfo.AppendLine(String.Format("Shipping: {0}", this.ShippingCharge));
orderInfo.AppendLine(String.Format("Total: {0}", this.Total())); return orderInfo.ToString(); }
} }

OrderSummaryView.cs

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace Agathas.Storefront.Services.ViewModels
{
public class OrderSummaryView
{
public int Id { get; set; }
public DateTime Created { get; set; }
public bool IsSubmitted { get; set; }
} }

第二步:启用配置:

        protected void Application_Start()
{ Services.AutoMapperBootStrapper.ConfigureAutoMapper();

第三步:使用:OrderMapper.cs

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Agathas.Storefront.Model.Orders;
using Agathas.Storefront.Services.ViewModels;
using AutoMapper; namespace Agathas.Storefront.Services.Mapping
{
public static class OrderMapper
{
public static OrderView ConvertToOrderView(this Order order)
{
return Mapper.Map<Order, OrderView>(order);
} public static IEnumerable<OrderSummaryView> ConvertToOrderSummaryViews(
this IEnumerable<Order> orders)
{
return Mapper.Map<IEnumerable<Order>, IEnumerable<OrderSummaryView>>(orders);
}
} }

在需要两个类型转换的地方调用:

 Order order = new 。。。;
OrderView orderView = order.ConvertToOrderView();
 OrderSummaryViews orderSummaryViews = new .....;
IEnumerable<OrderSummaryView> Orders = orderSummaryViews.ConvertToOrderSummaryViews()
上一篇:给 ecplise 配置struts2配置环境


下一篇:程序员的绘图利器 — Gnuplot