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