1 using System; 2 using System.Collections.Generic; 3 using System.Data; 4 using System.Reflection; 5 6 namespace Dll 7 { 8 public static class ToEntity 9 { 10 /// <summary> 11 /// 将DataTable转换成实体类 12 /// </summary> 13 /// <typeparam name="T">实体类</typeparam> 14 /// <param name="dt">DataTable</param> 15 /// <returns></returns> 16 public static List<T> DtConvertToModel<T>(DataTable dt) where T:new() 17 { 18 List<T> ts = new List<T>(); 19 foreach (DataRow dr in dt.Rows) 20 { 21 T t = new T(); 22 foreach (PropertyInfo pi in t.GetType().GetProperties()) 23 { 24 if (dt.Columns.Contains(pi.Name)) 25 { 26 if (!pi.CanWrite) continue; 27 var value = dr[pi.Name]; 28 if (value!= DBNull.Value) 29 { 30 switch (pi.PropertyType.FullName) 31 { 32 case "System.Decimal": 33 pi.SetValue(t, decimal.Parse(value.ToString()), null); 34 break; 35 case "System.String": 36 pi.SetValue(t, value.ToString(), null); 37 break; 38 case "System.Int32": 39 pi.SetValue(t, int.Parse(value.ToString()), null); 40 break; 41 default: 42 pi.SetValue(t, value, null); 43 break; 44 } 45 } 46 } 47 } 48 ts.Add(t); 49 } 50 return ts; 51 } 52 } 53 }