无影飞絮剑

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
 1     /// <summary>
 2     /// 数据表转换类
 3     /// </summary>
 4     /// <typeparam name="T"></typeparam>
 5     public class DbTableConvertor<T> where T : new()
 6     {
 7         /// <summary>
 8         /// 将DataTable转换为实体列表
 9         /// </summary>
10         /// <param name="dt">待转换的DataTable</param>
11         /// <returns></returns>
12         public List<T> ConvertToList(DataTable dt)
13         {
14             // 定义集合  
15             var list = new List<T>();
16 
17             if (0 == dt.Rows.Count)
18             {
19                 return list;
20             }
21 
22             // 获得此模型的可写公共属性  
23             IEnumerable<System.Reflection.PropertyInfo> propertys = new T().GetType().GetProperties().Where(u => u.CanWrite);
24             list = ConvertToEntity(dt, propertys);
25 
26 
27             return list;
28         }
29 
30         /// <summary>
31         /// 将DataTable的首行转换为实体
32         /// </summary>
33         /// <param name="dt">待转换的DataTable</param>
34         /// <returns></returns>
35         public T ConvertToEntity(DataTable dt)
36         {
37             DataTable dtTable = dt.Clone();
38             dtTable.Rows.Add(dt.Rows[0].ItemArray);
39             return ConvertToList(dtTable)[0];
40         }
41         private List<T> ConvertToEntity(DataTable dt, IEnumerable<System.Reflection.PropertyInfo> propertys)
42         {
43             var list = new List<T>();
44             //遍历DataTable中所有的数据行  
45             foreach (DataRow dr in dt.Rows)
46             {
47                 var entity = new T();
48 
49                 //遍历该对象的所有属性  
50                 foreach (System.Reflection.PropertyInfo p in propertys)
51                 {
52                     //将属性名称赋值给临时变量
53                     string tmpName = p.Name;
54 
55                     //检查DataTable是否包含此列(列名==对象的属性名)    
56                     if (!dt.Columns.Contains(tmpName)) continue;
57                     //取值  
58                     object value = dr[tmpName];
59                     //如果非空,则赋给对象的属性  
60                     if (value != DBNull.Value)
61                     {
62                         p.SetValue(entity, value, null);
63                     }
64                 }
65                 //对象添加到泛型集合中  
66                 list.Add(entity);
67             }
68             return list;
69         }
70     }
View Code

 

posted on 2017-11-16 09:37  无影飞絮剑  阅读(407)  评论(0编辑  收藏  举报