AutoMapperExtension
安装AutoMapper.Data程序包后,AutoMap才有了IDataReader的映射扩展功能,并且在AutoMap初始化配置的时候添加配置IDataReader的映射,如下面所示代码中
cfg.AddDataReaderMapping();
以下所示代码全部在程序包AutoMapper 8.0.0版本以及AutoMapper.Data为3.0.0版本进行开发的,如代码复制到项目中出现异常信息,请注意检查版本信息。附程序包nuget安装命令
install-package AutoMapper -version 8.0.0
install-package AutoMapper.Data -version 3.0.0
////// AutoMapper扩展 /// public static class AutoMapperExtension { /// /// 创建Mapper /// /// 要被转化的model /// 转化之后的model /// private static IMapper CreateMapper () { var config = new MapperConfiguration(cfg => { cfg.AddDataReaderMapping(); cfg.CreateMap (); }); ; var mapper = config.CreateMapper(); return mapper; } /// /// 创建Mapper /// /// 要被转化的model类型 /// 转化之后的model类型 /// private static IMapper CreateMapper(Type sourceType, Type destinationType) { var config = new MapperConfiguration(cfg => cfg.CreateMap(sourceType, destinationType)); ; var mapper = config.CreateMapper(); return mapper; } /// /// 类型映射 /// /// 转化之后的model /// 可以使用这个扩展方法的类型 /// 转化之后的实体 public static TDestination MapTo (this object obj) where TDestination : class { var mapper = CreateMapper(obj.GetType(), typeof(TDestination)); return mapper.Map (obj); } /// /// 类型映射 /// /// 转化之后的model /// 要被转化的model /// 可以使用这个扩展方法的类型 /// 转化之后的实体 public static TDestination MapTo (this TSource source) where TDestination : class where TSource : class { if (source == null) return default(TDestination); var mapper = CreateMapper (); return mapper.Map (source); } /// /// 类型映射,默认字段名字一一对应 /// /// 转化之后的model /// 要被转化的model /// 可以使用这个扩展方法的类型 /// 转化之后的实体 public static List MapTo (this IEnumerable source) where TDestination : class { if (source == null) return default(List ); var mapper = CreateMapper(source.AsQueryable().ElementType, typeof(TDestination)); return mapper.Map >(source); } ///
/// 类型映射 /// /// 转化之后的model /// 要被转化的model /// 可以使用这个扩展方法的类型 /// 转化之后的实体 public static List MapTo (this IEnumerable source) where TDestination : class where TSource : class { if (source == null) return default(List ); var mapper = CreateMapper (); return mapper.Map >(source); } ///
/// DataTable映射 /// /// 转化之后的model /// DataTable对象 /// public static List MapTo (this DataTable dt) where TDestination : class { if (dt == null || dt.Rows.Count == 0) return default(List ); var mapper = CreateMapper (); return mapper.Map >(dt.CreateDataReader()); } ///
/// DataSet映射 /// /// 转化之后的model /// DataSet对象 /// DataSet中要映射的DataTable的索引 /// public static List MapTo (this DataSet ds, int tableIndex = 0) where TDestination : class { if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0) return default(List ); var mapper = CreateMapper (); return mapper.Map >(ds.Tables[tableIndex].CreateDataReader()); } }