1 /// <summary>
2 /// AutoMapper扩展帮助类
3 /// </summary>
4 public static class AutoMapperHelper
5 {
6 /// <summary>
7 /// 类型映射
8 /// </summary>
9 public static T MapTo<T>(this object obj)
10 {
11 if (obj == null) return default(T);
12 Mapper.CreateMap(obj.GetType(), typeof(T));
13 return Mapper.Map<T>(obj);
14 }
15 /// <summary>
16 /// 集合列表类型映射
17 /// </summary>
18 public static List<TDestination> MapToList<TDestination>(this IEnumerable source)
19 {
20 foreach (var first in source)
21 {
22 var type = first.GetType();
23 Mapper.CreateMap(type, typeof(TDestination));
24 break;
25 }
26 return Mapper.Map<List<TDestination>>(source);
27 }
28 /// <summary>
29 /// 集合列表类型映射
30 /// </summary>
31 public static List<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source)
32 {
33 //IEnumerable<T> 类型需要创建元素的映射
34 Mapper.CreateMap<TSource, TDestination>();
35 return Mapper.Map<List<TDestination>>(source);
36 }
37 /// <summary>
38 /// 类型映射
39 /// </summary>
40 public static TDestination MapTo<TSource, TDestination>(this TSource source, TDestination destination)
41 where TSource : class
42 where TDestination : class
43 {
44 if (source == null) return destination;
45 Mapper.CreateMap<TSource, TDestination>();
46 return Mapper.Map(source, destination);
47 }
48 /// <summary>
49 /// DataReader映射
50 /// </summary>
51 public static IEnumerable<T> DataReaderMapTo<T>(this IDataReader reader)
52 {
53 Mapper.Reset();
54 Mapper.CreateMap<IDataReader, IEnumerable<T>>();
55 return Mapper.Map<IDataReader, IEnumerable<T>>(reader);
56 }
57 }
58 }