automapper初步
首先引入 automapper.dll
using System; using AutoMapper; namespace AutoMapperTest { class AutoMapperTest { /// <summary> /// Excute /// </summary> public static void Excute() { var order = new Order() { Id = 1, OrderName = "F", ClientName = "Aven", ClientId = 2 }; var orderBrief = OrderBrief.Create(order); } } class Order { public Int32 Id { get; set; } public string OrderName { get; set; } public string ClientName { get; set; } public Int32 ClientId { get; set; } } class OrderBrief { #region Mapper实现对应 static OrderBrief() { var map = Mapper.CreateMap<Order, OrderBrief>() // 默认自动映射所有命名一致的属性。 .ForMember(x => x.OrderId, y => y.MapFrom(z => z.Id)); // 显式映射不同名字。 map.BeforeMap((source, target) => { Console.WriteLine("做一些预处理"); }); map.AfterMap((source, target) => { Console.WriteLine("做一些后续处理"); }); } /// <summary> /// 必须放在该类中,且为静态方法.与静态构造函数一起使用 /// </summary> /// <param name="orderModel"></param> /// <returns></returns> public static OrderBrief Create(Order orderModel) { return Mapper.Map<Order, OrderBrief>(orderModel); } #endregion public Int32 OrderId { get; set; } public string OrderName { get; set; } public string ClientName { get; set; } } }