/// <summary>
/// 将datatable,装载成对象模式,对象模型的字段名需要与表里的字段名相同!
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> TableToEntity<T>(DataTable dt) where T : class,new()
{
Type type = typeof(T);
List<T> list = new List<T>();
foreach (DataRow row in dt.Rows)
{
PropertyInfo[] pArray = type.GetProperties();
T entity = new T();
foreach (PropertyInfo p in pArray)
{
if (row[p.Name] is Int64)
{
p.SetValue(entity, Convert.ToInt32(row[p.Name]), null);
continue;
}
else if (row[p.Name] is Int32)
{
p.SetValue(entity, Convert.ToInt32(row[p.Name]), null);
continue;
}
else if (row[p.Name] is UInt32)
{
p.SetValue(entity, Convert.ToInt32(row[p.Name]), null);
continue;
}
else if (row[p.Name] is DBNull)
{
p.SetValue(entity, "", null);
}
else
{
p.SetValue(entity, row[p.Name].ToString(), null);
}
}
list.Add(entity);
}
return list;
}
/// 将datatable,装载成对象模式,对象模型的字段名需要与表里的字段名相同!
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> TableToEntity<T>(DataTable dt) where T : class,new()
{
Type type = typeof(T);
List<T> list = new List<T>();
foreach (DataRow row in dt.Rows)
{
PropertyInfo[] pArray = type.GetProperties();
T entity = new T();
foreach (PropertyInfo p in pArray)
{
if (row[p.Name] is Int64)
{
p.SetValue(entity, Convert.ToInt32(row[p.Name]), null);
continue;
}
else if (row[p.Name] is Int32)
{
p.SetValue(entity, Convert.ToInt32(row[p.Name]), null);
continue;
}
else if (row[p.Name] is UInt32)
{
p.SetValue(entity, Convert.ToInt32(row[p.Name]), null);
continue;
}
else if (row[p.Name] is DBNull)
{
p.SetValue(entity, "", null);
}
else
{
p.SetValue(entity, row[p.Name].ToString(), null);
}
}
list.Add(entity);
}
return list;
}
本文介绍了一种将DataTable转换为特定类型对象集合的方法。通过反射机制,该方法能够将每一条数据记录映射到对应的对象属性上,支持多种数据类型转换,并能妥善处理DBNull值。
1753

被折叠的 条评论
为什么被折叠?



