简单来讲就是将一个对象映射到另外一个对象的代码。 摆脱了繁琐的赋值过程 (最多见也就是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();//好了。 基本的都搞好了。 如今测试一下能够 看到 已经映射上去了。 学习不能停下。 天天学习点。 会使本身变得越有价值