AutoMapperExt.cs 2.0 KB

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