Dynamic convert DataTable into entity collection -- 动态转换数据表成实体集合
在编程中,经常要将查询结果DataTable转换为实体集合,因为每个实体的属性都不一样,所以每个实体都要写专门的转换方法。
如果一个系统中有多个实体,几十上百个,哦,阿门,这种纯体力的劳动,对于作为将编程看作一门艺术的程序猿们,是无法忍受的!?
所以,对于这个在代码和技术含量上,严重影响了我们一行一行敲出来的艺术品的艺术性的问题,我们要解决它!
下面是我的解决办法
涉及技术:反射和泛型。
using System;
using System.Data;
using System.Reflection;
namespace DoubleFish.Database
{
/// < summary>
// DataTable扩展
/// </summary>
public static class DataTableExtension
{
/// <summary>
/// 将DataTable转换为对应的实体数组
/// </summary>
public static T[] ToArray(this DataTable dataTable) where T : new()
{
if (dataTable == null || dataTable.Rows.Count == 0)
return new T[] { };
// 定义集合
T[] array = new T[dataTable.Rows.Count];
// 获得此模型的类型
Type type = typeof(T);
T t = new T();
// 获得此模型的公共属性
PropertyInfo[] properties = t.GetType().GetProperties();
for (int i = 0; i < dataTable.Rows.Count; i++)
{
array[i] = new T();
foreach (PropertyInfo pi in properties)
{
// 检查DataTable是否包含此列
if (!dataTable.Columns.Contains(pi.Name))
continue;
// 判断此属性是否有Setter
if (!pi.CanWrite)
continue;
object value = dataTable.Rows[i][pi.Name];
if (value == DBNull.Value)
continue;
pi.SetValue(array[i], value, null);
}
}
}
return array;
}
}
还有 ToList(), ToModel 的原理和这个一样,就不贴了。
使用方法:
var ds = DbHelperSQL.Query(strSql, listPara.ToArray());
var array = ds.Tables[0].ToArray(); // DataTable To Array