1 using System;
2 using System.Collections.Generic;
3 using System.Data;
4 using System.Reflection;
5
6 /// <summary>
7 /// 将DataTable数据源转换成实体类
8 /// </summary>
9 /// <typeparam name="T">实体</typeparam>
10 public static class ToModel<T> where T : new()
11 {
12 /// <summary>
13 /// 将DataTable数据源转换成实体类
14 /// </summary>
15 public static List<T> ConvertToModel(DataTable dt)
16 {
17 List<T> ts = new List<T>();// 定义集合
18 foreach (DataRow dr in dt.Rows)
19 {
20 T t = new T();
21 PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
22 foreach (PropertyInfo pi in propertys)
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 }