C#把 DataTable转换为Model实体

    public static 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)
}
}
上一篇:asp.net core web项目目录解读


下一篇:实现Github和Coding仓库等Git服务托管更新