码迷,mamicode.com
首页 > 其他好文 > 详细

使用反射将DataTable的数据转成实体类

时间:2016-06-03 14:28:39      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:

利用反射避免了硬编码出现的错误,但是实体类的属性名必须和数据库名字对应(相同)

1、利用反射把DataTable的数据写到单个实体类

 1         /// <summary>
 2         /// 利用反射把DataTable的数据写到单个实体类
 3         /// </summary>
 4         /// <typeparam name="T"></typeparam>
 5         /// <param name="dtSource"></param>
 6         /// <returns></returns>
 7         public static T ToSingleEntity<T>(System.Data.DataTable dtSource)
 8         {
 9             if (dtSource == null)
10             {
11                 return default(T);
12             }
13 
14             if (dtSource.Rows.Count != 0)
15             {
16                 Type type = typeof(T);
17                 Object entity = Activator.CreateInstance(type);         //创建实例               
18                 foreach (PropertyInfo entityCols in type.GetProperties())
19                 {
20                     if (!string.IsNullOrEmpty(dtSource.Rows[0][entityCols.Name].ToString()))
21                     {
22                         entityCols.SetValue(entity, dtSource.Rows[0][entityCols.Name], null);
23                     }
24                 }
25                 return (T)entity;
26             }
27             return default(T);
28         }

2、利用反射把DataTable的数据写到集合实体类里

 1         /// <summary>
 2         /// 利用反射把DataTable的数据写到集合实体类里
 3         /// </summary>
 4         /// <typeparam name="T"></typeparam>
 5         /// <param name="dtSource"></param>
 6         /// <returns></returns>
 7         public static IEnumerable<T> ToListEntity<T>(System.Data.DataTable dtSource)
 8         {
 9             if (dtSource == null)
10             {
11                 return null;
12             }
13 
14             List<T> list = new List<T>();
15             Type type = typeof(T);
16             foreach (DataRow dataRow in dtSource.Rows)
17             {
18                 Object entity = Activator.CreateInstance(type);         //创建实例               
19                 foreach (PropertyInfo entityCols in type.GetProperties())
20                 {
21                     if (!string.IsNullOrEmpty(dataRow[entityCols.Name].ToString()))
22                     {
23                         entityCols.SetValue(entity, dataRow[entityCols.Name], null);
24                     }
25                 }
26                 list.Add((T)entity);
27             }
28             return list;
29         }

 

使用反射将DataTable的数据转成实体类

标签:

原文地址:http://www.cnblogs.com/linJie1930906722/p/5555928.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!