1、资源链接:
1、使用总结
2、对象映射工具
3、简介
4、基本用法
5、官方手册
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoMapper;
using System.Collections;
using System.Data;
using System.Reflection;namespace NFMES.Core.Type
{public static class AutoMapperExtension{public static TDestination MapTo<TDestination>(this object o){if (o &#61;&#61; null)throw new ArgumentNullException();Mapper.CreateMap(o.GetType(), typeof(TDestination));return Mapper.Map<TDestination>(o); ;}public static List<TDestination> MapTo<TDestination>(this IEnumerable o){if (o &#61;&#61; null)throw new ArgumentNullException();foreach (var item in o){Mapper.CreateMap(item.GetType(), typeof(TDestination));break;}return Mapper.Map<List<TDestination>>(o);}public static List<T> MapTo<T>(this DataTable dt){if (dt &#61;&#61; null || dt.Rows.Count &#61;&#61; 0)return default(List<T>);Mapper.CreateMap<IDataReader, T>();return Mapper.Map<List<T>>(dt.CreateDataReader());}public static DataTable MapToTable<T>(this IEnumerable list){if (list &#61;&#61; null)return default(DataTable);List<PropertyInfo> pList &#61; new List<PropertyInfo>();System.Type type &#61; typeof(T);DataTable dt &#61; new DataTable();Array.ForEach<PropertyInfo>(type.GetProperties(), p &#61;> { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });foreach (var item in list){DataRow row &#61; dt.NewRow();pList.ForEach(p &#61;> row[p.Name] &#61; p.GetValue(item, null));dt.Rows.Add(row);}return dt;}}
}
这个静态类中有4个扩展方法&#xff0c;分别对Object类型&#xff0c;IEnumberable类型&#xff0c;DataTable类型添加了MapTo方法&#xff0c;可以方便的将对象映射到对象&#xff0c;集合映射到集合&#xff0c;表映射到集合&#xff0c;集合映射到表&#xff08;这个功能AutoMapper不支持&#xff0c;我用反射实现的&#xff09;
单实体转化使用方式&#xff1a;
集合转化的使用方式&#xff1a;