using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection; namespace Dll
{
public static class ToEntity
{
/// <summary>
/// 将DataTable转换成实体类
/// </summary>
/// <typeparam name="T">实体类</typeparam>
/// <param name="dt">DataTable</param>
/// <returns></returns>
public static List<T> DtConvertToModel<T>(DataTable dt) where T:new()
{
List<T> ts = new List<T>();
foreach (DataRow dr in dt.Rows)
{
T t = new T();
foreach (PropertyInfo pi in t.GetType().GetProperties())
{
if (dt.Columns.Contains(pi.Name))
{
if (!pi.CanWrite) continue;
var value = dr[pi.Name];
if (value!= DBNull.Value)
{
switch (pi.PropertyType.FullName)
{
case "System.Decimal":
pi.SetValue(t, decimal.Parse(value.ToString()), null);
break;
case "System.String":
pi.SetValue(t, value.ToString(), null);
break;
case "System.Int32":
pi.SetValue(t, int.Parse(value.ToString()), null);
break;
default:
pi.SetValue(t, value, null);
break;
}
}
}
}
ts.Add(t);
}
return ts;
}
}
}
05-13 21:49