什么是AutoMapper?
簡單來說就是將一個對象映射到另一個對象的代碼。 擺脫了繁瑣的賦值過程 (最常見也就是Model -——ViewModel)
AutoMapper安裝
我使用的是VS2015 可以在NuGet中直接輸入AutoMapper 去下載
也可以使用控制台命令
PM> Install-Package AutoMapper
這里我定義了兩個類 ShopingInfo ShopingInfoViewModel
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;
然后 專門建了一個類用來存放這些映射關系SourceProfile 並且繼承了 Profile
public class SourceProfile : Profile { public SourceProfile() { base.CreateMap<ShopingInfo, ShopingInfoViewModel>(); } }
如果 我們發現兩類中有字段名不一致。
例如 我吧shopingInfoViewModel 中的 ShopingName 改為 Name 那你可以這樣寫
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();//好了。 基本的都搞好了。 現在測試一下可以 看到 已經映射上去了。 學習不能停下。 每天學習點。 會使自己變得越有價值