You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
65 lines
2.4 KiB
65 lines
2.4 KiB
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
|
|
namespace ICSSoft.Frame.Common
|
|
{
|
|
using System.Data;
|
|
using System.Reflection;
|
|
|
|
/// <summary>
|
|
/// 将DataTable数据源转换成实体类
|
|
/// </summary>
|
|
/// <typeparam name="T">实体</typeparam>
|
|
public static class ToModel<T> where T : new()
|
|
{
|
|
|
|
/// <summary>
|
|
/// 将DataTable数据源转换成实体类
|
|
/// </summary>
|
|
public static List<T> ConvertToModel(DataTable dt)
|
|
{
|
|
List<T> ts = new List<T>();
|
|
foreach (DataRow dr in dt.Rows)
|
|
{
|
|
T t = new T();
|
|
PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
|
|
foreach (PropertyInfo pi in propertys)
|
|
{
|
|
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;
|
|
case "System.Guid":
|
|
pi.SetValue(t, new System.Guid(value.ToString()), null);
|
|
break;
|
|
case "System.Double":
|
|
pi.SetValue(t, Convert.ToDouble(value ?? 0), null);
|
|
break;
|
|
default:
|
|
pi.SetValue(t, value, null);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
ts.Add(t);
|
|
}
|
|
return ts;
|
|
}
|
|
}
|
|
}
|