在开始本篇文章以前,先来思考一个问题:一个项目分多层架构,如显示层、业务逻辑层、服务层、数据访问层。层与层访问须要数据载体,也就是类。若是多层通用一个类,一则会暴露出每层的字段,两者会使类字段不少,并且会出现不少冗余字段,这种方式是不可取的;若是每层都使用不一样的类,则层与层调用时,一个字段一个字段的赋值又会很麻烦。针对第二种状况,可使用AutoMapper来帮助咱们实现类字段的赋值及转换。html
AutoMapper是一个对象映射器,它能够将一个一种类型的对象转换为另外一种类型的对象。AutoMapper提供了映射规则及操做方法,使咱们不用过多配置就能够映射两个类。架构
经过Nuget安装AutoMapper,本次使用版本为6.2.2。app
先建立两个类用于映射:ui
public class ProductEntity { public string Name { get; set; } public decimal Amount { get; set; } } public class ProductDTO { public string Name { get; set; } public decimal Amount { get; set; } }
Automapper可使用静态类和实例方法来建立映射,下面分别使用这两种方式来实现 ProductEntity -> ProductDTO的映射。spa
Mapper.Initialize(cfg => cfg.CreateMap<ProductEntity, ProductDTO>()); var productDTO = Mapper.Map<ProductDTO>(productEntity);
MapperConfiguration configuration = new MapperConfiguration(cfg => cfg.CreateMap<ProductEntity, ProductDTO>()); var mapper = configuration.CreateMapper(); var productDTO = mapper.Map<ProductDTO>(productEntity);
完整的例子:orm
[TestMethod] public void TestInitialization() { var productEntity = new ProductEntity() { Name = "Product" + DateTime.Now.Ticks, Amount = 10 }; Mapper.Initialize(cfg => cfg.CreateMap<ProductEntity, ProductDTO>()); var productDTO = Mapper.Map<ProductDTO>(productEntity); Assert.IsNotNull(productDTO); Assert.IsNotNull(productDTO.Name); Assert.IsTrue(productDTO.Amount > 0); }
除了使用以上两总方式类配置映射关系,也可使用Profie配置来实现映射关系。htm
建立自定义的Profile须要继承Profile类:对象
public class MyProfile : Profile { public MyProfile() { CreateMap<ProductEntity, ProductDTO>(); // Other mapping configurations } }
完成例子:blog
[TestMethod] public void TestProfile() { var productEntity = new ProductEntity() { Name = "Product" + DateTime.Now.Ticks, Amount = 10 }; var configuration = new MapperConfiguration(cfg => cfg.AddProfile<MyProfile>()); var productDTO = configuration.CreateMapper().Map<ProductDTO>(productEntity); Assert.IsNotNull(productDTO); Assert.IsNotNull(productDTO.Name); Assert.IsTrue(productDTO.Amount > 0); }
除了使用AddProfile,也可使用AddProfiles添加多个配置;一样,能够同时使用Mapper和Profile,也能够添加多个配置:继承
var configuration = new MapperConfiguration(cfg => { cfg.AddProfile<MyProfile>(); cfg.CreateMap<ProductEntity, ProductDTO>(); });
AutoMapper先映射名字一致的字段,若是没有,则会尝试使用如下规则来映射:
先建立用到的映射类:
public class Product { public Supplier Supplier { get; set; } public string Name { get; set; } public decimal GetAmount() { return 10; } } public class Supplier { public string Name { get; set; } } public class ProductDTO { public string SupplierName { get; set; } public decimal Amount { get; set; } }
AutoMapper会自动实现Product.Supplier.Name -> ProductDTO.SupplierName, Product.GetTotal -> ProductDTO.Total的映射。
[TestMethod] public void TestFalttening() { var supplier = new Supplier() { Name = "Supplier" + DateTime.Now.Ticks }; var product = new Product() { Supplier = supplier, Name = "Product" + DateTime.Now.Ticks }; Mapper.Initialize(cfg => cfg.CreateMap<Product, ProductDTO>()); var productDTO = Mapper.Map<ProductDTO>(product); Assert.IsNotNull(productDTO); Assert.IsNotNull(productDTO.SupplierName); Assert.IsTrue(productDTO.Amount > 0); }
AutoMapper除了能够映射单个对象外,也能够映射集合对象。AutoMapper源集合类型支持如下几种:
简单类型映射:
public class Source { public int Value { get; set; } } public class Destination { public int Value { get; set; } } [TestMethod] public void TestCollectionSimple() { Mapper.Initialize(cfg => cfg.CreateMap<Source, Destination>()); var sources = new[] { new Source {Value = 1}, new Source {Value = 2}, new Source {Value = 3} }; IEnumerable<Destination> ienumerableDest = Mapper.Map<Source[], IEnumerable<Destination>>(sources); ICollection<Destination> icollectionDest = Mapper.Map<Source[], ICollection<Destination>>(sources); IList<Destination> ilistDest = Mapper.Map<Source[], IList<Destination>>(sources); List<Destination> listDest = Mapper.Map<Source[], List<Destination>>(sources); Destination[] arrayDest = Mapper.Map<Source[], Destination[]>(sources); }
复杂对象映射:
public class Order { private IList<OrderLine> _lineItems = new List<OrderLine>(); public OrderLine[] LineItems { get { return _lineItems.ToArray(); } } public void AddLineItem(OrderLine orderLine) { _lineItems.Add(orderLine); } } public class OrderLine { public int Quantity { get; set; } } public class OrderDTO { public OrderLineDTO[] LineItems { get; set; } } public class OrderLineDTO { public int Quantity { get; set; } } [TestMethod] public void TestCollectionNested() { Mapper.Initialize(cfg => { cfg.CreateMap<Order, OrderDTO>(); cfg.CreateMap<OrderLine, OrderLineDTO>(); }); var order = new Order(); order.AddLineItem(new OrderLine {Quantity = 10}); order.AddLineItem(new OrderLine {Quantity = 20}); order.AddLineItem(new OrderLine {Quantity = 30}); var orderDTO = Mapper.Map<OrderDTO>(order); Assert.IsNotNull(orderDTO); Assert.IsNotNull(orderDTO.LineItems); Assert.IsTrue(orderDTO.LineItems.Length > 0); }
除了以上使用的自动映射规则,AutoMapper还能够指定映射方式。下面使用ForMemeber指定字段的映射,将一个时间值拆分映射到日期、时、分:
public class Calendar { public DateTime CalendarDate { get; set; } public string Title { get; set; } } public class CalendarModel { public DateTime Date { get; set; } public int Hour { get; set; } public int Minute { get; set; } public string Title { get; set; } } [TestMethod] public void TestProjection() { var calendar = new Calendar() { Title = "2018年日历", CalendarDate = new DateTime(2018, 1, 1, 11, 59, 59) }; Mapper.Initialize(cfg => cfg .CreateMap<Calendar, CalendarModel>() .ForMember(dest => dest.Date, opt => opt.MapFrom(src =>src.CalendarDate.Date)) .ForMember(dest => dest.Hour, opt => opt.MapFrom(src => src.CalendarDate.Hour)) .ForMember(dest => dest.Minute, opt => opt.MapFrom(src => src.CalendarDate.Minute))); var calendarModel = Mapper.Map<CalendarModel>(calendar); Assert.AreEqual(calendarModel.Date.Ticks, new DateTime(2018, 1, 1).Ticks); Assert.AreEqual(calendarModel.Hour, 11); Assert.AreEqual(calendarModel.Minute, 59); }
有些状况下,咱们会考虑添加映射条件,好比,某个值不符合条件时,不容许映射。针对这种状况可使用ForMember中的Condition:
public class Source { public int Value { get; set; } } public class Destination { public uint Value { get; set; } } [TestMethod] public void TestConditionByCondition() { var source = new Source() { Value = 3 }; //若是Source.Value > 0, 则执行映射;不然,映射失败 Mapper.Initialize(cfg => cfg .CreateMap<Source, Destination>() .ForMember(dest => dest.Value, opt => opt.Condition(src => src.Value > 0))); var destation = Mapper.Map<Destination>(source); //若是不符合条件,则抛出异常 Assert.IsTrue(destation.Value.Equals(3)); }
若是要映射的类符合必定的规则,并且有不少,针对每一个类都建立一个CreaterMapper会很麻烦。可使用AddConditionalObjectMapper指定对象映射规则,这样就不用每一个映射关系都添加一个CreateMapper。另外,也可使用AddMemberConfiguration指定字段的映射规则,好比字段的先后缀:
public class Product { public string Name { get; set; } public int Count { get; set; } } public class ProductModel { public string NameModel { get; set; } public int CountMod { get; set; } } [TestMethod] public void TestConditionByConfiguration() { var product = new Product() { Name = "Product" + DateTime.Now.Ticks, Count = 10 }; var config = new MapperConfiguration(cfg => { //对象映射规则: 经过如下配置,能够映射全部”目标对象的名称“等于“源对象名称+Model”的类,而不用单个添加CreateMapper映射 cfg.AddConditionalObjectMapper().Where((s, d) => d.Name == s.Name + "Model"); //字段映射规则: 经过如下配置,能够映射“源字段”与“目标字段+Model或Mod”的字段 cfg.AddMemberConfiguration().AddName<PrePostfixName>(_ => _.AddStrings(p => p.DestinationPostfixes, "Model", "Mod")); }); var mapper = config.CreateMapper(); var productModel = mapper.Map<ProductModel>(product); Assert.IsTrue(productModel.CountMod == 10); }
须要注意的一点是,添加了以上配置,若是目标对象中有字段没有映射到,则会抛出异常。
若是配置了值转换,AutoMapper会将修改转换后的值以符合配置的规则。好比,配置目标对象中的值添加符号“@@”:
public class Source { public string Name { get; set; } } public class Destination { public string Name { get; set; } } [TestMethod] public void TestValueTransfer() { var source = new Source() { Name = "Bob" }; Mapper.Initialize(cfg => { cfg.CreateMap<Source, Destination>(); cfg.ValueTransformers.Add<string>(val => string.Format("@{0}@", val)); }); var destation = Mapper.Map<Destination>(source); Assert.AreEqual("@Bob@", destation.Name); }
若是要映射的值为Null,则可使用NullSubstitute指定Null值的替换值:
public class Source { public string Name { get; set; } } public class Destination { public string Name { get; set; } } [TestMethod] public void TestValueTransfer() { var source = new Source() { }; Mapper.Initialize(cfg => { cfg.CreateMap<Source, Destination>() .ForMember(dest => dest.Name, opt => opt.NullSubstitute("其余值")); }); var destation = Mapper.Map<Destination>(source); Assert.AreEqual("其余值", destation.Name); }
配置了映射,可是如何肯定是否映射成功或者是否有字段没有映射呢?能够添加Mapper.AssertConfigurationIsValid();来验证是否映射成功。默认状况下,目标对象中的字段都被映射到后,AssertConfigurationIsValid才会返回True。也就是说,源对象必须包含全部目标对象,这样在大多数状况下不是咱们想要的,咱们可使用下面的方法来指定验证规则:
public class Product { public string Name { get; set; } public int Amount { get; set; } } public class ProductModel { public string Name { get; set; } public int Amount { get; set; } public string ViewName { get; set; } } public class ProductDTO { public string Name { get; set; } public int Amount { get; set; } public string ViewName { get; set; } } [TestMethod] public void TestValidation() { var product = new Product() { Name = "Product" + DateTime.Now.Ticks, Amount = 10 }; Mapper.Initialize(cfg => { //1. 指定字段映射方式 cfg.CreateMap<Product, ProductModel>() .ForMember(dest => dest.ViewName, opt => opt.Ignore()); //若是不添加此设置,会抛出异常 //2. 指定整个对象映射方式 //MemberList: // Source: 检查源对象全部字段映射成功 // Destination:检查目标对象全部字段映射成功 // None: 跳过验证 cfg.CreateMap<Product, ProductDTO>(MemberList.Source); }); var productModel = Mapper.Map<ProductModel>(product); var productDTO = Mapper.Map<ProductDTO>(product); //验证映射是否成功 Mapper.AssertConfigurationIsValid(); }
有的时候你可能会在建立映射先后对数据作一些处理,AutoMapper就提供了这种方式:
public class Source { public string Name { get; set; } public int Value { get; set; } } public class Destination { public string Name { get; set; } public int Value { get; set; } } [TestMethod] public void TestBeforeOrAfter() { var source = new Source() { Name = "Product" + DateTime.Now.Ticks, }; Mapper.Initialize(cfg => { cfg.CreateMap<Source, Destination>() .BeforeMap((src, dest) => src.Value = src.Value + 10) .AfterMap((src, dest) => dest.Name = "Pobin"); }); var productModel = Mapper.Map<Destination>(source); Assert.AreEqual("Pobin", productModel.Name); }
从6.1.0开始,AutoMapper经过调用Reverse能够实现反向映射。反向映射根据初始化时建立的正向映射规则来作反向映射:
public class Order { public decimal Total { get; set; } public Customer Customer { get; set; } } public class Customer { public string Name { get; set; } } public class OrderDTO { public decimal Total { get; set; } public string CustomerName { get; set; } } [TestMethod] public void TestReverseMapping() { var customer = new Customer { Name = "Tom" }; var order = new Order { Customer = customer, Total = 20 }; Mapper.Initialize(cfg => { cfg.CreateMap<Order, OrderDTO>() .ForMember(dest => dest.CustomerName, opt => opt.MapFrom(src => src.Customer.Name)) //正向映射规则 .ReverseMap(); //设置反向映射 }); //正向映射 var orderDTO = Mapper.Map<OrderDTO>(order); //反向映射:使用ReverseMap,不用再建立OrderDTO -> Order的映射,并且还能保留正向的映射规则 var orderConverted = Mapper.Map<Order>(orderDTO); Assert.IsNotNull(orderConverted.Customer); Assert.AreEqual("Tom", orderConverted.Customer.Name); }
若是反向映射中不想使用原先的映射规则,也能够取消掉:
Mapper.Initialize(cfg => { cfg.CreateMap<Order, OrderDTO>() .ForMember(dest => dest.CustomerName, opt => opt.MapFrom(src => src.Customer.Name)) //正向映射规则 .ReverseMap() .ForPath(src => src.Customer.Name, opt => opt.Ignore()); //设置反向映射 });
有些状况下目标字段类型和源字段类型不一致,能够经过类型转换器实现映射,类型转换器有三种实现方式:
void ConvertUsing(Func<TSource, TDestination> mappingFunction); void ConvertUsing(ITypeConverter<TSource, TDestination> converter); void ConvertUsing<TTypeConverter>() where TTypeConverter : ITypeConverter<TSource, TDestination>;
下面经过一个例子来演示下以上三种类型转换器的使用方式:
namespace AutoMapperSummary { [TestClass] public class CustomerTypeConvert { public class Source { public string Value1 { get; set; } public string Value2 { get; set; } public string Value3 { get; set; } } public class Destination { public int Value1 { get; set; } public DateTime Value2 { get; set; } public Type Value3 { get; set; } } public class DateTimeTypeConverter : ITypeConverter<string, DateTime> { public DateTime Convert(string source, DateTime destination, ResolutionContext context) { return System.Convert.ToDateTime(source); } } public class TypeTypeConverter : ITypeConverter<string, Type> { public Type Convert(string source, Type destination, ResolutionContext context) { return Assembly.GetExecutingAssembly().GetType(source); } } [TestMethod] public void TestTypeConvert() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<string, int>().ConvertUsing((string s) => Convert.ToInt32(s)); cfg.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter()); cfg.CreateMap<string, Type>().ConvertUsing<TypeTypeConverter>(); cfg.CreateMap<Source, Destination>(); }); config.AssertConfigurationIsValid(); //验证映射是否成功 var source = new Source { Value1 = "20", Value2 = "2018/1/1", Value3 = "AutoMapperSummary.CustomerTypeConvert+Destination" }; var mapper = config.CreateMapper(); var destination = mapper.Map<Source, Destination>(source); Assert.AreEqual(typeof(Destination), destination.Value3); } } }
使用AutoMapper的自带解析规则,咱们能够很方便的实现对象的映射。好比:源/目标字段名称一致,“Get/get + 源字段“与"目标字段"一致等。除了这些简单的映射,还可使用ForMember指定字段映射。可是,某些状况下,解析规则会很复杂,使用自带的解析规则没法实现。这时能够自定义解析规则,能够经过如下三种方式使用自定义的解析器:
ResolveUsing<TValueResolver> ResolveUsing(typeof(CustomValueResolver)) ResolveUsing(aValueResolverInstance)
下面经过一个例子来演示如何使用自定义解析器:
public class Source { public string FirstName { get; set; } public string LastName { get; set; } } public class Destination { public string Name { get; set; } } /// <summary> /// 自定义解析器: 组合姓名 /// </summary> public class CustomResolver : IValueResolver<Source, Destination, string> { public string Resolve(Source source, Destination destination, string destMember, ResolutionContext context) { if (source != null && !string.IsNullOrEmpty(source.FirstName) && !string.IsNullOrEmpty(source.LastName)) { return string.Format("{0} {1}", source.FirstName, source.LastName); } return string.Empty; } } [TestMethod] public void TestResolver() { Mapper.Initialize(cfg => cfg.CreateMap<Source, Destination>() .ForMember(dest => dest.Name, opt => opt.ResolveUsing<CustomResolver>())); Mapper.AssertConfigurationIsValid(); var source = new Source { FirstName = "Michael", LastName = "Jackson" }; var destination = Mapper.Map<Source, Destination>(source); Assert.AreEqual("Michael Jackson", destination.Name); }
AutoMapper功能很强大,自定义配置支持也很是好,可是真正项目中使用时却不多用到这么多功能,并且通常都会对AutoMapper进一步封装使用。一方面使用起来方面,另一方面也可使代码统一。下面的只是作一个简单的封装,还须要结合实际项目使用:
/// <summary> /// AutoMapper帮助类 /// </summary> public class AutoMapperManager { private static readonly MapperConfigurationExpression MapperConfiguration = new MapperConfigurationExpression(); static AutoMapperManager() { } private AutoMapperManager() { AutoMapper.Mapper.Initialize(MapperConfiguration); } public static AutoMapperManager Instance { get; } = new AutoMapperManager(); /// <summary> /// 添加映射关系 /// </summary> /// <typeparam name="TSource"></typeparam> /// <typeparam name="TDestination"></typeparam> public void AddMap<TSource, TDestination>() where TSource : class, new() where TDestination : class, new() { MapperConfiguration.CreateMap<TSource, TDestination>(); } /// <summary> /// 获取映射值 /// </summary> /// <typeparam name="TDestination"></typeparam> /// <param name="source"></param> /// <returns></returns> public TDestination Map<TDestination>(object source) where TDestination : class, new() { if (source == null) { return default(TDestination); } return Mapper.Map<TDestination>(source); } /// <summary> /// 获取集合映射值 /// </summary> /// <typeparam name="TDestination"></typeparam> /// <param name="source"></param> /// <returns></returns> public IEnumerable<TDestination> Map<TDestination>(IEnumerable source) where TDestination : class, new() { if (source == null) { return default(IEnumerable<TDestination>); } return Mapper.Map<IEnumerable<TDestination>>(source); } /// <summary> /// 获取映射值 /// </summary> /// <typeparam name="TSource"></typeparam> /// <typeparam name="TDestination"></typeparam> /// <param name="source"></param> /// <returns></returns> public TDestination Map<TSource, TDestination>(TSource source) where TSource : class, new () where TDestination : class, new() { if (source == null) { return default(TDestination); } return Mapper.Map<TSource, TDestination>(source); } /// <summary> /// 获取集合映射值 /// </summary> /// <typeparam name="TSource"></typeparam> /// <typeparam name="TDestination"></typeparam> /// <param name="source"></param> /// <returns></returns> public IEnumerable<TDestination> Map<TSource, TDestination>(IEnumerable<TSource> source) where TSource : class, new() where TDestination : class, new() { if (source == null) { return default(IEnumerable<TDestination>); } return Mapper.Map<IEnumerable<TSource>, IEnumerable<TDestination>>(source); } /// <summary> /// 读取DataReader内容 /// </summary> /// <typeparam name="TDestination"></typeparam> /// <param name="reader"></param> /// <returns></returns> public IEnumerable<TDestination> Map<TDestination>(IDataReader reader) { if (reader == null) { return new List<TDestination>(); } var result = Mapper.Map<IEnumerable<TDestination>>(reader); if (!reader.IsClosed) { reader.Close(); } return result; } }
本篇文章列举了AutoMapper的基本使用方式,更多的使用能够参考官方文档:http://automapper.readthedocs.io/en/latest/index.html