using System;
|
using System.Collections.Generic;
|
using System.Data;
|
using System.Linq;
|
using System.Reflection;
|
using System.Web;
|
|
namespace JiangSu.cs
|
{
|
/// <summary>
|
/// DataTable与实体类相互转换
|
/// </summary>
|
public class ModelHandler
|
{
|
/// <summary>
|
/// 填充对象列表
|
/// </summary>
|
public static List<T> FillModel<T>(DataTable dt) where T : new()
|
{
|
if (dt == null || dt.Rows.Count == 0)
|
{
|
return null;
|
}
|
|
List<T> list = new List<T>();
|
BindingFlags flag = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance;
|
PropertyInfo[] pis = typeof(T).GetProperties();
|
|
foreach (DataRow dr in dt.Rows)
|
{
|
T t = new T();
|
foreach (PropertyInfo pi in pis)
|
{
|
object val = dr[pi.Name] == DBNull.Value ? null : dr[pi.Name];
|
t.GetType().GetProperty(pi.Name, flag).SetValue(t, val, null);
|
}
|
|
list.Add(t);
|
}
|
|
return list;
|
}
|
|
/// <summary>
|
/// 填充DataTable
|
/// </summary>
|
public static DataTable FillDataTable<T>(List<T> list) where T : new()
|
{
|
if (list == null || list.Count == 0)
|
{
|
return null;
|
}
|
|
DataTable dt = CreateDataTable<T>();
|
PropertyInfo[] pis = typeof(T).GetProperties();
|
|
foreach (T t in list)
|
{
|
DataRow dr = dt.NewRow();
|
foreach (PropertyInfo pi in pis)
|
{
|
dr[pi.Name] = pi.GetValue(t, null);
|
}
|
}
|
|
return dt;
|
}
|
|
/// <summary>
|
/// 创建DataTable
|
/// </summary>
|
public static DataTable CreateDataTable<T>() where T : new()
|
{
|
DataTable dt = new DataTable(typeof(T).Name);
|
|
PropertyInfo[] pis = typeof(T).GetProperties();
|
foreach (PropertyInfo pi in pis)
|
{
|
dt.Columns.Add(new DataColumn(pi.Name, pi.PropertyType));
|
}
|
|
return dt;
|
}
|
}
|
}
|