111
yantian yue
2023-12-28 7820f50a29b75e0704e6e1dcfdaf2e85397c66a8
提交 | 用户 | 时间
e46d3b 1 using System;
2 using System.Collections.Generic;
3 using System.Data;
4 using System.Linq;
5 using System.Text;
6
7 namespace YX.BLL
8 {
9     public  class DataTableToModel
10     {
11         //数据库查出来的表名必须与实体表名一致
12       
13         public static T GetEntity<T>(DataTable table) where T : new()
14         {
15             T entity = new T();
16             foreach (DataRow row in table.Rows)
17             {
18                 foreach (var item in entity.GetType().GetProperties())
19                 {
20                     if (row.Table.Columns.Contains(item.Name))
21                     {
22                         if (DBNull.Value != row[item.Name])
23                         {
24                             item.SetValue(entity, Convert.ChangeType(row[item.Name], item.PropertyType), null);
25                         }
26                     }
27                 }
28             }
29             return entity;
30         }
31         public static IList<T> GetEntities<T>(DataTable table) where T : new()
32         {
33             IList<T> entities = new List<T>();
34             foreach (DataRow row in table.Rows)
35             {
36                 T entity = new T();
37                 foreach (var item in entity.GetType().GetProperties())
38                 {
39                     item.SetValue(entity, Convert.ChangeType(row[item.Name], item.PropertyType), null);
40                 }
41                 entities.Add(entity);
42             }
43             return entities;
44         }       
45     }
46 }