将DataTable转为Model

View Code
 1  /// <summary>
2 /// 将DataTable转为Model
3 /// </summary>
4 /// <param name="dt">DataTable</param>
5 /// <returns>泛型实体集合</returns>
6 public static IList<T> ToModels(DataTable dt)
7 {
8 IList<T> ts = new List<T>();
9 // 获得此模型的类型
10 Type type = typeof(T);
11 string tempName = "";
12 foreach (DataRow dr in dt.Rows)
13 {
14 T t = new T();
15 // 获得此模型的公共属性
16 PropertyInfo[] propertys = t.GetType().GetProperties();
17 foreach (PropertyInfo pi in propertys)
18 {
19 tempName = pi.Name;
20 // 检查DataTable是否包含此列
21 if (dt.Columns.Contains(tempName))
22 {
23 // 判断此属性是否有Setter
24 if (!pi.CanWrite)
25 continue;
26 object value = dr[tempName];
27 if (value != DBNull.Value)
28 {
29 if (pi.PropertyType.IsEnum)
30 {
31 pi.SetValue(t, Enum.Parse(pi.PropertyType, value.ToString().Trim(), true), null);
32 }
33 else if (pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
34 {
35 pi.SetValue(t, Convert.ChangeType(value, System.Nullable.GetUnderlyingType(pi.PropertyType)), null);
36 }
37 else
38 {
39 pi.SetValue(t, Convert.ChangeType(value, pi.PropertyType), null);
40 }
41 }
42 }
43 }
44 ts.Add(t);
45 }
46 return ts;
47 }

 

posted @ 2012-01-29 14:20  名字随意  阅读(184)  评论(0编辑  收藏  举报