using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Epost.Common { /// /// 实体转换辅助类 /// public class ModelConvertHelper where T : new() { /// /// 将DataTable转换为实体列表 /// 作者: oldman /// 创建时间: 2015年9月13日 /// /// 待转换的DataTable /// public static List ConvertToList(DataTable dt) { // 定义集合 var list = new List(); if (0 == dt.Rows.Count) { return list; } // 获得此模型的可写公共属性 IEnumerable propertys = new T().GetType().GetProperties().Where(u => u.CanWrite); list = ConvertToEntity(dt, propertys); return list; } /// /// 将DataTable的首行转换为实体 /// 作者: oldman /// 创建时间: 2015年9月13日 /// /// 待转换的DataTable /// public static T ConvertToEntity(DataTable dt) { DataTable dtTable = dt.Clone(); dtTable.Rows.Add(dt.Rows[0].ItemArray); return ConvertToList(dtTable)[0]; } private static List ConvertToEntity(DataTable dt, IEnumerable propertys) { var list = new List(); ////遍历DataTable中所有的数据行 //foreach (DataRow dr in dt.Rows) //{ // var entity = new T(); // //遍历该对象的所有属性 // foreach (PropertyInfo p in propertys) // { // //将属性名称赋值给临时变量 // string tmpName = p.Name; // //检查DataTable是否包含此列(列名==对象的属性名) // if (!dt.Columns.Contains(tmpName)) continue; // //取值 // object value = dr[tmpName]; // //如果非空,则赋给对象的属性 // if (value != DBNull.Value) // { // p.SetValue(entity, Convert.ChangeType(value, p.PropertyType), null); // } // } // //对象添加到泛型集合中 // list.Add(entity); //} List modelList = new List(); foreach (DataRow dr in dt.Rows) { //T model = (T)Activator.CreateInstance(typeof(T)); T model = new T(); for (int i = 0; i < dr.Table.Columns.Count; i++) { PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName); if (propertyInfo != null && dr[i] != DBNull.Value) propertyInfo.SetValue(model, dr[i], null); } modelList.Add(model); } return modelList; } } }