AutoMapper扩展方法
DTO框架AutoMapper,知道很久了,今天有个前辈说好像最新版本不能用了,网上示例不行了,自己下载源码看了一下,琢磨了一下
写了一个简易版的
源git地址:
https://github.com/AutoMapper/AutoMapper
1 调用 2 DataTable tblDatas = new DataTable("Datas"); 3 tblDatas.Columns.Add("ID", typeof(int)); 4 tblDatas.Columns.Add("Product", typeof(string)); 5 tblDatas.Columns.Add("Version", typeof(string)); 6 tblDatas.Columns.Add("Description", typeof(string)); 7 tblDatas.Rows.Add(new object[] { 1, "a", "b", "c" }); 8 tblDatas.Rows.Add(new object[] { 2, "a", "b", "c" }); 9 tblDatas.Rows.Add(new object[] { 3, "a", "b", "c" }); 10 tblDatas.Rows.Add(new object[] { 4, "a", "b", "c" }); 11 tblDatas.Rows.Add(new object[] { 5, "a", "b", "c" }); 12 13 Mapper.Initialize(config => 14 { 15 config.CreateMapInformat<DataRow, Source>(); 16 config.CreateMapInformat<Source, Target>(); 17 }); 18 var source = tblDatas.Rows.OfType<DataRow>().Select(item => Mapper.Map<DataRow, Source>(item)).ToList(); 19 var list = Mapper.Map<List<Source>, List<Target>>(source);
1 对应的实体类代码 2 public class Target 3 { 4 public int ID { get; set; } 5 public string Product { get; set; } 6 public string Version { get; set; } 7 public string Description { get; set; } 8 } 9 10 public class Source 11 { 12 public int ID { get; set; } 13 public string Product { get; set; } 14 public string Version { get; set; } 15 public string Description { get; set; } 16 }
扩展方法
1 public static class MapperExtens 2 { 3 public static void CreateMapInformat<TSource, TDestination>( this IMapperConfigurationExpression config) 4 { 5 var sourceType = typeof(TSource); 6 var destinationType = typeof(TDestination); 7 8 config.CreateProfile(sourceType.Name, (profile) => 9 { 10 if (sourceType.IsGenericType) 11 { 12 sourceType = sourceType.GetGenericTypeDefinition(); 13 } 14 15 if (destinationType.IsGenericType) 16 { 17 destinationType = destinationType.GetGenericTypeDefinition(); 18 } 19 20 var map = profile.CreateMap<TSource, TDestination>(); 21 foreach (var property in destinationType.GetProperties()) 22 { 23 map.ForMember(property.Name, opt => opt.MapFrom(s => Reflex(s, property))); 24 } 25 26 }); 27 } 28 29 private static object Reflex<TSource>(TSource source, PropertyInfo property) 30 { 31 return DefaultForType(source, property); 32 } 33 34 private static object DefaultForType<TSource>(TSource source, PropertyInfo property) 35 { 36 if (source.GetType() == typeof(DataRow)) 37 { 38 return (source as DataRow)?[property.Name]; 39 } 40 41 return FindPropertyInfo(source, property); 42 } 43 44 private static object FindPropertyInfo<TSource>(TSource source, PropertyInfo property) 45 { 46 if (typeof(TSource).IsValueType) 47 { 48 return Activator.CreateInstance(property.PropertyType); 49 } 50 else 51 { 52 return typeof(TSource).GetProperty(property.Name)?.GetValue(source); 53 } 54 } 55 }