将DataRow读取到的一行 转为 Model

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

 

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