AutoMapper扩展方法

幽映每白日,清辉照衣裳。这篇文章主要讲述AutoMapper扩展方法相关的知识,希望能为你提供帮助。
DTO框架AutoMapper,知道很久了,今天有个前辈说好像最新版本不能用了,网上示例不行了,自己下载源码看了一下,琢磨了一下
写了一个简易版的
源git地址:
【AutoMapper扩展方法】https://github.com/AutoMapper/AutoMapper
 

1 调用 2DataTable tblDatas = new DataTable("Datas"); 3tblDatas.Columns.Add("ID", typeof(int)); 4tblDatas.Columns.Add("Product", typeof(string)); 5tblDatas.Columns.Add("Version", typeof(string)); 6tblDatas.Columns.Add("Description", typeof(string)); 7tblDatas.Rows.Add(new object[] { 1, "a", "b", "c" }); 8tblDatas.Rows.Add(new object[] { 2, "a", "b", "c" }); 9tblDatas.Rows.Add(new object[] { 3, "a", "b", "c" }); 10tblDatas.Rows.Add(new object[] { 4, "a", "b", "c" }); 11tblDatas.Rows.Add(new object[] { 5, "a", "b", "c" }); 12 13Mapper.Initialize(config => 14{ 15config.CreateMapInformat< DataRow, Source> (); 16config.CreateMapInformat< Source, Target> (); 17}); 18var source = tblDatas.Rows.OfType< DataRow> ().Select(item => Mapper.Map< DataRow, Source> (item)).ToList(); 19var list = Mapper.Map< List< Source> , List< Target> > (source);

1 对应的实体类代码 2public class Target 3{ 4public int ID { get; set; } 5public string Product { get; set; } 6public string Version { get; set; } 7public string Description { get; set; } 8} 9 10public class Source 11{ 12public int ID { get; set; } 13public string Product { get; set; } 14public string Version { get; set; } 15public string Description { get; set; } 16}

 
扩展方法
1public static class MapperExtens 2{ 3public static void CreateMapInformat< TSource, TDestination> ( this IMapperConfigurationExpression config) 4{ 5var sourceType = typeof(TSource); 6var destinationType = typeof(TDestination); 7 8config.CreateProfile(sourceType.Name, (profile) => 9{ 10if (sourceType.IsGenericType) 11{ 12sourceType = sourceType.GetGenericTypeDefinition(); 13} 14 15if (destinationType.IsGenericType) 16{ 17destinationType = destinationType.GetGenericTypeDefinition(); 18} 19 20var map = profile.CreateMap< TSource, TDestination> (); 21foreach (var property in destinationType.GetProperties()) 22{ 23map.ForMember(property.Name, opt => opt.MapFrom(s => Reflex(s, property))); 24} 25 26}); 27} 28 29private static object Reflex< TSource> (TSource source, PropertyInfo property) 30{ 31return DefaultForType(source, property); 32} 33 34private static object DefaultForType< TSource> (TSource source, PropertyInfo property) 35{ 36if (source.GetType() == typeof(DataRow)) 37{ 38return (source as DataRow)?[property.Name]; 39} 40 41return FindPropertyInfo(source, property); 42} 43 44private static object FindPropertyInfo< TSource> (TSource source, PropertyInfo property) 45{ 46if (typeof(TSource).IsValueType) 47{ 48return Activator.CreateInstance(property.PropertyType); 49} 50else 51{ 52return typeof(TSource).GetProperty(property.Name)?.GetValue(source); 53} 54} 55}

 

    推荐阅读