C# AutoMapper的简单扩展

时间:2024-05-12 08:36:02

AutoMapper可以很方便的将一个实体的属性值转化给另一个对象。这个功能在我们日常的编码中经常会遇到。我将AutoMapper的一些基本映射功能做成扩展方法,在编码中更方便使用。

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
{
/// <summary>
/// 实体对象转换
/// </summary>
/// <typeparam name="TDestination"></typeparam>
/// <param name="o"></param>
/// <returns></returns>
public static TDestination MapTo<TDestination>(this object o)
{
if (o == null)
throw new ArgumentNullException(); Mapper.CreateMap(o.GetType(), typeof(TDestination)); return Mapper.Map<TDestination>(o); ;
} /// <summary>
/// 集合转换
/// </summary>
/// <typeparam name="TDestination"></typeparam>
/// <param name="o"></param>
/// <returns></returns>
public static List<TDestination> MapTo<TDestination>(this IEnumerable o)
{
if (o == null)
throw new ArgumentNullException(); foreach (var item in o)
{
Mapper.CreateMap(item.GetType(), typeof(TDestination)); break;
}
return Mapper.Map<List<TDestination>>(o);
} /// <summary>  
/// 将 DataTable 转为实体对象  
/// </summary>  
/// <typeparam name="T"></typeparam>  
/// <param name="dt"></param>  
/// <returns></returns>  
public static List<T> MapTo<T>(this DataTable dt)
{
if (dt == null || dt.Rows.Count == )
return default(List<T>); Mapper.CreateMap<IDataReader, T>();
return Mapper.Map<List<T>>(dt.CreateDataReader());
} /// <summary>
/// 将List转换为Datatable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static DataTable MapToTable<T>(this IEnumerable list)
{
if (list == null)
return default(DataTable); //创建属性的集合
List<PropertyInfo> pList = new List<PropertyInfo>();
//获得反射的入口
System.Type type = typeof(T);
DataTable dt = new DataTable();
//把所有的public属性加入到集合 并添加DataTable的列
Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });
foreach (var item in list)
{
//创建一个DataRow实例
DataRow row = dt.NewRow();
//给row 赋值
pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
//加入到DataTable
dt.Rows.Add(row);
}
return dt;
} }
}

这个静态类中有4个扩展方法,分别对Object类型,IEnumberable类型,DataTable类型添加了MapTo方法,可以方便的将对象映射到对象,集合映射到集合,表映射到集合,集合映射到表(这个功能AutoMapper不支持,我用反射实现的)

单实体转化使用方式:

C# AutoMapper的简单扩展

集合转化的使用方式:

C# AutoMapper的简单扩展

AutoMapper还有很多功能,我这个类只扩展了一些最基本和常用的功能,以后用到会继续添加。

相关文章