编程语言
首页 > 编程语言> > C# DataTable映射成Entity

C# DataTable映射成Entity

作者:互联网

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel.DataAnnotations.Schema;
 4 using System.Data;
 5 using System.Reflection;
 6 using System.Text;
 7 
 8 namespace TJCFinanceWriteOff.BizLogic.Common
 9 {
10     public class DataTableUtil
11     {
12         /// <summary>
13         /// 将DataRow转换为实体对象
14         /// </summary>
15         /// <typeparam name="T"></typeparam>
16         /// <param name="dr"></param>
17         /// <returns></returns>
18         public static T ConvertToEntity<T>(DataRow dr) where T : new()
19         {
20             T entity = new T();
21             Type info = typeof(T);
22             var properties = info.GetProperties();
23             string columnName = string.Empty;
24             foreach (var prop in properties)
25             {
26                 //1.判断该属性是否可写
27                 if (!prop.CanWrite)
28                 {
29                     continue;
30                 }
31                 //2.查看实体类是否有数据库相关特性,没有则以属性名作为名称
32                 var attributes = prop.GetCustomAttribute<ColumnAttribute>();
33                 if (attributes is null)
34                 {
35                     columnName = prop.Name;
36                 }
37                 else
38                 {
39                     columnName = attributes.Name;
40                 }
41                 //3.判断数据列中是否包含此实体属性
42                 if (!dr.Table.Columns.Contains(columnName))
43                 {
44                     continue;
45                 }
46                 object value = dr[columnName];
47                 if (value != DBNull.Value)
48                 {
49                     //根据ColumnName,将dr中的相对字段赋值给Entity属性
50                     prop.SetValue(entity, Convert.ChangeType(value, prop.PropertyType), null);
51                 }
52             }
53             return entity;
54         }
55 
56         /// <summary>
57         /// 
58         /// </summary>
59         /// <typeparam name="T"></typeparam>
60         /// <param name="dt"></param>
61         /// <returns></returns>
62         public static List<T> ToEntityList<T>(DataTable dt) where T : new()
63         {
64             List<T> list = new List<T>(dt.Rows.Count);
65             foreach (DataRow dr in dt.Rows)
66             {
67                 list.Add(ConvertToEntity<T>(dr));
68             }
69             return list;
70         }
71     }
72 }

 

标签:C#,System,Entity,columnName,new,using,prop,dr,DataTable
来源: https://www.cnblogs.com/fanqisoft/p/11671428.html