using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Reflection; namespace DS.Module.FastReport { /// /// 实体转换辅助类 /// public static class ModelConvertHelper { /// /// 转为List /// /// /// public static List ToModelList(this DataTable dt) where T : new() { // 定义集合 List ts = new List(); // 获得此模型的类型 Type type = typeof(T); string tempName = null, tempDescription = null; foreach (DataRow dr in dt.Rows) { T t = new T(); // 获得此模型的公共属性 PropertyInfo[] propertys = t.GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { // 检查DataTable是否包含此列 tempName = pi.Name; tempDescription = pi == null ? null : ((DescriptionAttribute)Attribute.GetCustomAttribute(pi, typeof(DescriptionAttribute))) ?.Description; string column = tempDescription ?? tempName; if (dt.Columns.Contains(column)) { // 判断此属性是否有Setter if (!pi.CanWrite) continue; object value = dr[column]; if (value != DBNull.Value) { if (pi.PropertyType.ToString().Contains("System.Nullable")) value = Convert.ChangeType(value, Nullable.GetUnderlyingType(pi.PropertyType)); else value = Convert.ChangeType(value, pi.PropertyType); pi.SetValue(t, value, null); } } } ts.Add(t); } return ts; } /// /// 将实体集合转换为DataTable /// /// 实体类型 /// 实体集合 public static DataTable ToDataTable(this IList entities) { var result = CreateTable(); FillData(result, entities); return result; } /// /// 创建表 /// private static DataTable CreateTable() { var result = new DataTable(); var type = typeof(T); foreach (var property in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)) { var propertyType = property.PropertyType; if ((propertyType.IsGenericType) && (propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))) propertyType = propertyType.GetGenericArguments()[0]; result.Columns.Add(property.Name, propertyType); } return result; } /// /// 填充数据 /// private static void FillData(DataTable dt, IEnumerable entities) { foreach (var entity in entities) { dt.Rows.Add(CreateRow(dt, entity)); } } /// /// 创建行 /// private static DataRow CreateRow(DataTable dt, T entity) { DataRow row = dt.NewRow(); var type = typeof(T); foreach (var property in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)) { row[property.Name] = property.GetValue(entity) ?? DBNull.Value; } return row; } /// /// 转换为List, 仅转一 列 /// /// /// /// /// public static List ToSimpleList(this DataTable dt, int column = 0) { // 定义集合 List ts = new List(); foreach (DataRow dr in dt.Rows) { T t = (T)dr[column]; ts.Add(t); } return ts; } } }