官方项目下载:

http://automapper.codeplex.com/

博文

http://www.iteye.com/blogs/tag/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()

【AutoMapper】实体类间自动实现映射关系,及其转换。的更多相关文章

  1. mybatis逆向工程自动生成实体类、接口以及映射Mapper.xml配置文件

    Mybatis的逆向工程非常简单,只要一个配置文件和一个Main方法就可以实现,下面以maven工程为例: (1)在pom.xml中引入依赖包 <dependency> <group ...

  2. 通过数据库中的表,使用 MyEclipse2017的反向生成工具-->hibernate反转引擎引擎(MyEclipse2017自带的插件) 来反转生成实体类和对应的映射文件

    通过数据库中的表,使用 MyEclipse2017的反向生成工具-->hibernate反转引擎引擎(MyEclipse2017自带的插件) 来反转生成实体类和对应的映射文件   文章目录 Ja ...

  3. C#实体类null自动转空字符串

    C#实体类null自动转空字符串 using System.ComponentModel.DataAnnotations; [DisplayFormat(ConvertEmptyStringToNul ...

  4. EntityFramework 系列:实体类配置-根据依赖配置关系和关联

    EF实体类的配置可以使用数据注释或Fluent API两种方式配置,Fluent API配置的关键在于搞清实体类的依赖关系,按此方法配置,快速高效合理.为了方便理解,我们使用简化的实体A和B以及A.B ...

  5. Entity Framework 6 Code First 实践系列(1):实体类配置-根据依赖配置关系和关联

    EF实体类的配置可以使用数据注释或Fluent API两种方式配置,Fluent API配置的关键在于搞清实体类的依赖关系,按此方法配置,快速高效合理.为了方便理解,我们使用简化的实体A和B以及A.B ...

  6. 【转】Entity Framework 6 Code First 实践系列(1):实体类配置-根据依赖配置关系和关联

    本文转自:http://www.cnblogs.com/easygame/p/3622893.html EF实体类的配置可以使用数据注释或Fluent API两种方式配置,Fluent API配置的关 ...

  7. Hibernate用注解实现实体类和表的映射

    数据库mysql: 1.一对一 person50表password50表是一对一的关系: password50表中有外键 person_id person实体类: package com.c50.en ...

  8. mybatis的基本配置:实体类、配置文件、映射文件、工具类 、mapper接口

    搭建项目 一:lib(关于框架的jar包和数据库驱动的jar包) 1,第一步:先把mybatis的核心类库放进lib里

  9. Hibernate 由实体类与配置文件的配置关系生成数据库中的表

    import org.hibernate.cfg.Configuration; import org.hibernate.tool.hbm2ddl.SchemaExport; public class ...

随机推荐

  1. 20150320--安全性,Membership类

    安全性--验证与授权,成员资格与角色. 一.成员资格与角色, 第一步:注册数据库,在VS中运行dos命令窗口中,输入:aspnet_regsql,建立数据库表. 如何启动VS的dos命令窗口,在  . ...

  2. 【ASP.NET】获取网站目录的方法

         获取网站物理路径: HttpRuntime.AppDomainAppPath 获取网站虚拟路径: HttpRuntime.AppDomainAppVirtualPath

  3. 8款效果惊艳的HTML5 3D动画

    1.HTML5 WebGL水面水波荡漾特效 之前已经向各位分享过一款很逼真的HTML5水波荡漾特效,效果还算不错.今天再向大家分享一款更加给力的HTML5水波动画,画面上是一个大水池,水池底部是一颗大 ...

  4. Socket 广播

    1.广播端口 Socket中的广播端口是什么意思,是谁对应谁的? 这个广播端口 指定 客户端接收广播消息时要使用的端口号. 参考: 1.快速Python 原型 2.receive UDP broadc ...

  5. [译] 开发者角度,王道之论:Android 与 Windows Phone

    前几天,在codeproject搜索Silverlight资料,偶然看到这篇文章,耐心读了2遍,非常不错:文章通过访谈聊天形式叙述,2位主角目前在<斯法克斯国家工程学院>软件学院上学. 周 ...

  6. 近期H5项目开发小结

    前言:2016差不多又过了半啦,最近参与了公司好几个h5项目(严格来说,也只能算是推广页面活动).主要是新品牌的推广需要,当然也有给公司以前老客户做的案例.今天主要总结下为新品牌开发的2个h5推广:就 ...

  7. [大牛翻译系列]Hadoop(21)附录D.1 优化后的重分区框架

    附录D.1 优化后的重分区框架 Hadoop社区连接包需要将每个键的所有值都读取到内存中.如何才能在reduce端的连接减少内存开销呢?本文提供的优化中,只需要缓存较小的数据集,然后在连接中遍历较大数 ...

  8. PHP取二进制文件头快速判断文件类型的实现代码

    通过读取文件头信息来识别文件的真实类型. 一般我们都是按照文件扩展名来判断文件类型,但是这个很不靠谱,轻易就通过修改扩展名来躲避了,一般必须要读取文件信息来识别,PHP扩展中提供了类似 exif_im ...

  9. HTML5 input新增的几种类型(数字、日期、颜色选取、范围)

    你可能已经听说过,HTML5里引入了几种新的input类型.在HTML5之前,大家熟知的input类型包括:text(输入框),hidden(隐藏域),submit(提交按钮)等.而HTML5到来之后 ...

  10. openerp模块收藏 基于Lodop的报表打印模块(转载)

    基于Lodop的报表打印模块 原文:http://shine-it.net/index.php/topic,7397.0.html 前段时间写了个小模块,来解决OE中报表打印不方便的问题.借鉴了 @b ...