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.
64 lines
1.8 KiB
64 lines
1.8 KiB
9 months ago
|
using System;
|
||
|
using System.Collections.Generic;
|
||
|
using System.Data;
|
||
|
using System.Reflection;
|
||
|
|
||
|
namespace FangYar.BLL
|
||
|
{
|
||
|
/// <summary>
|
||
|
/// DataTable 转 实体类
|
||
|
/// </summary>
|
||
|
public class CommomModelBLL
|
||
|
{
|
||
|
public List<T> GetModelFromDB<T>(DataTable dt)
|
||
|
{
|
||
|
List<T> data = new List<T>();
|
||
|
foreach (DataRow row in dt.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())
|
||
|
{
|
||
|
if (dr[column.ColumnName] == DBNull.Value)
|
||
|
{
|
||
|
pro.SetValue(obj, " ", null);
|
||
|
break;
|
||
|
}
|
||
|
else
|
||
|
{
|
||
|
pro.SetValue(obj, dr[column.ColumnName], null);
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
return obj;
|
||
|
}
|
||
|
catch (Exception ex)
|
||
|
{
|
||
|
throw new Exception(ex.Message);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|