创建实体类代码

 1 public class DataToEnity<T> where T : new()
 2     {
 3         public static T DataRowToEntity(DataRow dr)
 4         {
 5             //1.获取类型
 6             Type type = typeof(T);
 7             //2.创建实例
 8             T temp = Activator.CreateInstance<T>();
 9             //3.获取属性
10             PropertyInfo[] properties = type.GetProperties();
11             // 4.遍历属性,对属性设置 对应的值
12             foreach (PropertyInfo p in properties)
13             {
14                 //5. 判断 属性名称是否出现在 这个表的列明中
15                 if (dr.Table.Columns.Contains(p.Name))
16                 {
17                     //6.判断  列中的值是否为 “空”
18                     if (dr[p.Name] == DBNull.Value)
19                     {
20                         continue;
21                     }
22                     Type pt = p.PropertyType;
23                     // 对可空类型的处理
24                     if (pt.IsGenericType && pt.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
25                     {
26                         // 获取  可空类型 的 基类型
27                         NullableConverter nc = new NullableConverter(pt);
28                         pt = nc.UnderlyingType;
29                     }
30                     object tempValue = Convert.ChangeType(dr[p.Name], pt);
31                     p.SetValue(temp, tempValue);
32                 }
33             }
34 
35 
36 
37 
38 
39             return temp;
40         }
41 
42     }

没有上面的方法 就要 调用工具类  需要转换实体的方法

//#region 转换实体
//private Article DataRowToEntity(DataRow dr)
//{
// Article article = new Article();

// article.ArticleID = dr["ArticleID"].ToString();

// article.Title = dr["Title"].ToString();

// article.Content = dr["Content"].ToString();

// article.OrderBy = Convert.ToInt32(dr["OrderBy"]);

// article.CreaterId = dr["CreaterId"].ToString();

// article.CreateTime = Convert.ToDateTime(dr["CreateTime"]);

// article.SummaryImg = dr["SummaryImg"].ToString();

// return article;
//}
//#endregion

posted on 2017-10-24 21:25  CCCCCC1129  阅读(283)  评论(0编辑  收藏  举报

导航