1、AutoMapper简介
用于两个对象映射,例如把Model的属性值赋值给View Model。传统写法会一个一个属性的映射很麻烦,使用AutoMapper两句代码搞定。
2、AutoMapper安装
推荐使用nuget搜索AutoMapper安装
3、AutoMapper简单用法
先建个model
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace cms.Web.Models {public class book { public int ID { get; set; } public string name { get; set; } public string className { get; set; } } public class bookViewModel { public int ID { get; set; } public string name { get; set; } public string className { get; set; } public int price { get; set; } public string des { get; set; } } }
controller代码
public object ceshi() { book data = new book { ID = 1, name = "少年1号", className = "娱乐" }; //映射初始化写法1 Mapper.Initialize(x => x.CreateMap<book, bookViewModel>()); ////映射初始化写法2 //Mapper.Initialize(config => //{ // config.CreateMap<book, bookViewModel>(); //}); ////映射初始化写法3 //var cfg = new MapperConfigurationExpression(); //cfg.CreateMap<book, bookViewModel>(); //cfg.CreateMap<bookViewModel, book>(); //Mapper.Initialize(cfg); //映射-写法1:由AutoMapper创建目标对象 var vmodel = Mapper.Map<book, bookViewModel>(data); //映射 - 写法2:让AutoMapper把源对象中的属性值合并 / 覆盖到目标对象(推荐) bookViewModel vmodel2 = new bookViewModel(); Mapper.Map(data, vmodel2); //return vmodel.ToString(); return JsonConvert.DeserializeObject(JsonConvert.SerializeObject(vmodel2)); }
4、AutoMapper高级用法
https://www.cnblogs.com/youring2/p/automapper.html
http://www.cnblogs.com/1-2-3/p/AutoMapper-Best-Practice.html