这里写自定义目录标题
public class DBTableHelper<T>
{
/// <summary>
/// datatable 转model
/// </summary>
/// <param name="table"></param>
/// <returns></returns>
public static List<T> DataTableToModel(DataTable table)
{
List<T> data = new List<T>();
foreach (DataRow row in table.Rows)
{
T item = GetItem<T>(row);
data.Add(item);
}
return data;
}
/// <summary>
/// 将DataRow转换成实体对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dr"></param>
/// <returns></returns>
private static T GetItem<T>(DataRow dr)
{
try
{
Type temp = typeof(T);
T obj = Activator.CreateInstance<T>();
foreach (DataColumn column in dr.Table.Columns)
{
foreach (PropertyInfo pro in temp.GetProperties())
{
if (pro.Name.ToLower() == column.ColumnName.ToLower())
{
var VAL = dr[column.ColumnName];
//var type = VAL.GetType();
bool bol =typeof(Int64) == VAL.GetType();
bool str=typeof(DBNull) ==pro.Name.GetType();
bool date = typeof(MySqlDateTime) == VAL.GetType();
if (VAL == DBNull.Value)
{
pro.SetValue(obj, null, null);
break;
}
else
{
//如果是datetime
if (date)
{
VAL = VAL.ToString();
}
pro.SetValue(obj, bol? Convert.ToInt32(VAL) : VAL, null);
break;
}
}
}
}
return obj;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}