簡單來講就是將一個對象映射到另外一個對象的代碼。 擺脫了繁瑣的賦值過程 (最多見也就是Model -——ViewModel)app
我使用的是VS2015 能夠在NuGet中直接輸入AutoMapper 去下載學習
也能夠使用控制檯命令測試
PM> Install-Package AutoMapperspa
這裏我定義了兩個類 ShopingInfo ShopingInfoViewModelcode
public class ShopingInfo:EntityBase { public string ShopingName { get; set; } public int ShopingCount { get; set; } public decimal ShopingPric { get; set; } public int Stock { get; set; } public int Volumeofvolume { get; set; } public int ShopingTypeId { get; set; } public virtual ShopingType ShopingType { get; set; } }
public class ShopingInfoViewModel { public int ID { get; set; } public string ShopingName { get; set; } public int ShopingCount { get; set; } public decimal ShopingPric { get; set; } public int Stock { get; set; } public int Volumeofvolume { get; set; } public string ShopingTypeName { get; set; } }
須要用到的命名空間對象
using AutoMapper;blog
而後 專門建了一個類用來存放這些映射關係SourceProfile 而且繼承了 Profile繼承
public class SourceProfile : Profile { public SourceProfile() { base.CreateMap<ShopingInfo, ShopingInfoViewModel>(); } }
若是 咱們發現兩類中有字段名不一致。 ci
例如 我吧shopingInfoViewModel 中的 ShopingName 改成 Name 那你能夠這樣寫get
public class SourceProfile : Profile { public SourceProfile() { base.CreateMap<ShopingInfo, ShopingInfoViewModel>(); // base.CreateMap<ShopingInfo, ShopingInfoViewModel>().ForMember(x => x.Name, // q => { q.MapFrom(z => z.ShopingName); // }); } }
建了箇中間類 用來封裝上面的代碼
public class AutoMapper { public static void Start() { Mapper.Initialize(x => { x.AddProfile<SourceProfile>(); }); } }
而後就在全局類Global中 使得 啓動初始化就去加載 加入下面這句代碼
AutoMapper.Start();//好了。 基本的都搞好了。 如今測試一下能夠 看到 已經映射上去了。 學習不能停下。 天天學習點。 會使本身變得越有價值