1.引用命名空间
using AutoMapper;
using AutoMapper.Mappers;
2.实体类和dto
public class Order { public int orderid { get; set; } public decimal amount { get; set; } public string address { get; set; } }
public class OrderDto { public int orderid { get; set; } public decimal amount { get; set; } public string address { get; set; } }
3.controller里的代码
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using AutoMapper; using AutoMapper.Mappers; using AutoMaperTest.Models.Entity; using AutoMaperTest.Models.Dto; namespace AutoMaperTest.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { Mapper.CreateMap<Models.Entity.Order,Models.Dto.OrderDto>(); //初始化 Order o = new Order(){ orderid=100,amount=101,address="beijing" }; OrderDto od=Mapper.Map<OrderDto>(o); //开始映射 Response.Write("entity->dto:"+od.address); OrderDto odnew = new OrderDto { orderid=1,amount=10,address="china" }; Order onew = Mapper.Map<Order>(odnew); Response.Write("dto->entity:"+onew.address); List<Order> lt = new List<Order>(); lt.Add(o); List<OrderDto> ltod = new List<OrderDto>(); lt.Each(temp => { ltod.Add(Mapper.Map<OrderDto>(temp)); }); Response.Write("</br>this is list<>映射:" + ltod[0].address); return View(); } } }
方法2:程序启动时 初始化映射
1.添加一个myprofile 类,让其继承:Profile ,重写方法
protected override void Configure()
{
CreateMap<Models.Entity.Order, Models.Dto.OrderDto>(); //Tsource,Tdestin
CreateMap<Models.Dto.OrderDto, Models.Entity.Order>();
}
2.添加一个 Configuration 类
编写一个静态方法,以便在application_start 里 注册该方法
public static void ConfigureNew()
{
Mapper.Initialize(cfg =>
{
cfg.AddProfile<Profiles.OrderProfile>();
// cfg.AddProfile<Profiles.OrderDtoProfile>();
});
}
在 global.ascx 里 注册 AutoMaperTest.AutoMaper.Configuration.ConfigureNew(); //初始化
参考:http://www.cnblogs.com/youring2/p/automapper.html