using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Reflection;
using System.Text; namespace TJCFinanceWriteOff.BizLogic.Common
{
public class DataTableUtil
{
/// <summary>
/// 将DataRow转换为实体对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dr"></param>
/// <returns></returns>
public static T ConvertToEntity<T>(DataRow dr) where T : new()
{
T entity = new T();
Type info = typeof(T);
var properties = info.GetProperties();
string columnName = string.Empty;
object propName = DBNull.Value;
foreach (var prop in properties)
{
//1.判断该属性是否可写
if (!prop.CanWrite)
{
continue;
}
//2.查看实体类是否有数据库相关特性,没有则以属性名作为名称
var attributes = prop.GetCustomAttribute<ColumnAttribute>(); if (attributes is null)
{
columnName = prop.Name;
}
else
{
columnName = attributes.Name ?? prop.Name;
}
if (!dr.Table.Columns.Contains(columnName))
{
continue;
}
propName = dr[columnName];
if (propName != DBNull.Value)
{
//根据ColumnName,将dr中的相对字段赋值给Entity属性
prop.SetValue(entity, Convert.ChangeType(propName, prop.PropertyType), null);
}
}
return entity;
} /// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> ToEntityList<T>(DataTable dt) where T : new()
{
List<T> list = new List<T>(dt.Rows.Count);
foreach (DataRow dr in dt.Rows)
{
list.Add(ConvertToEntity<T>(dr));
}
return list;
}
}
}

最新文章

  1. 阿里云安装Tomcat
  2. AC自动机 &amp; Fail树 专题练习
  3. 查看图片真正的格式,在不知道扩展名的情况下区分是jpeg还是bmp
  4. java 验证电话号码(手机和固话)
  5. spring4 定时任务
  6. UVALive 6088 Approximate Sorting 构造题
  7. Oracle数据库之动态SQL
  8. 由浅入深吃透MVC框架,驯服烂代码
  9. 我用爬虫一天时间“偷了”知乎一百万用户,只为证明PHP是世界上最好的语言
  10. HTMLElement
  11. 2.1 insertion sort 《算法导论》答案
  12. 洛谷 [P2146] 软件包管理器
  13. pip install 提示&quot;no previously-included directories found matching&quot;及&quot;no previously-included files matching found anywhere in distribution&quot;,且偶发无法关联安装 PyPI 库的故障
  14. python自动化开发-[第十八天]-django的ORM补充与ajax,分页器
  15. ShoppingCart类图
  16. P2789 直线交点数
  17. Create-React-App脚手架使用方法
  18. C#创建文件夹和文件
  19. elasticsearch ik中文分词器的安装配置使用
  20. 【U3D】播放器设置(PlayerSettings)

热门文章

  1. Java面向对象6(AA ~ AE)
  2. Simple Problem with Integers(POJ 3486)
  3. windows游戏编程封装窗口类
  4. 安装curl依赖库后yum不能使用问题解决
  5. Linux 配置eth0网卡
  6. Flutter移动电商实战 --(37)路由_Fluro引入和商品详细页建立
  7. Event---事件详解
  8. Vue生命周期钩子函数加载顺序的理解
  9. Qt编写自定义控件23-广告轮播控件
  10. 一百三十八:CMS系统之发布帖子前端js