using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Reflection; namespace Ant.ORM { /// /// DataTable与实体类互相转换 /// /// 实体类 public class DataTableModelHelp where T : new() { #region DataTable转换成实体类 /// /// 填充对象列表:用DataSet的第一个表填充分体类 /// /// DataSet /// public List FillModel(DataSet ds) { if (ds == null || ds.Tables[0] == null || ds.Tables[0].Rows.Count == 0) { return null; } else { return FillModel(ds.Tables[0]); } } /// /// 填充对象列表:用DataSet的第index个表填充分体类 /// public List FillModel(DataSet ds, int index) { if (ds == null || ds.Tables.Count <= index || ds.Tables[index].Rows.Count == 0) { return null; } else { return FillModel(ds.Tables[index]); } } /// /// 填充对象列表:用DataTable填充分体类 /// public List FillModel(DataTable dt) { if (dt == null || dt.Rows.Count == 0) { return null; } List modelList = new List(); foreach (DataRow dr in dt.Rows) { //T model = (T)Activator.CreateInstance(typeof(T)); T model = new T(); foreach (PropertyInfo propertyInfo in typeof(T).GetProperties()) { model.GetType().GetProperty(propertyInfo.Name).SetValue(model, dr[propertyInfo.Name], null); } modelList.Add(model); } return modelList; } /// /// 填充对象:用DataRow填充分体类 /// public T FillModel(DataRow dr) { if (dr == null) { return default(T); } //T model = (T)Activator.CreateInstance(typeof(T)); T model = new T(); foreach (PropertyInfo propertyInfo in typeof(T).GetProperties()) { model.GetType().GetProperty(propertyInfo.Name).SetValue(model, dr[propertyInfo.Name], null); } return model; } #endregion #region 实体类转换成DataTable /// /// 实体类转换成DataSet /// /// 实体类列表 /// public DataSet FillDataSet(List modelList) { if (modelList == null || modelList.Count == 0) { return null; } else { DataSet ds = new DataSet(); ds.Tables.Add(FillDataTable(modelList)); return ds; } } /// /// 实体类转换成DataTable /// /// 实体类列表 /// public DataTable FillDataTable(List modelList) { if (modelList == null || modelList.Count == 0) { return null; } DataTable dt = CreateData(modelList[0]); foreach (T model in modelList) { DataRow dataRow = dt.NewRow(); foreach (PropertyInfo propertyInfo in typeof(T).GetProperties()) { dataRow[propertyInfo.Name] = propertyInfo.GetValue(model, null); } dt.Rows.Add(dataRow); } return dt; } /// /// 按照实体类获得表布局 /// /// 实体类 /// private DataTable CreateData(T model) { DataTable dataTable = new DataTable(typeof(T).Name); foreach (PropertyInfo propertyInfo in typeof(T).GetProperties()) { dataTable.Columns.Add(new DataColumn(propertyInfo.Name, propertyInfo.PropertyType)); } return dataTable; } #endregion } }