using System; using System.Collections.Generic; using System.Data; using System.Reflection; namespace FangYar.BLL { /// /// DataTable 转 实体类 /// public class CommomModelBLL { public List GetModelFromDB(DataTable dt) { List data = new List(); foreach (DataRow row in dt.Rows) { T item = GetItem(row); data.Add(item); } return data; } /// /// 将DataRow转换成实体对象 /// /// /// /// private static T GetItem(DataRow dr) { try { Type temp = typeof(T); T obj = Activator.CreateInstance(); 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); } } } }