C# DataTable映射成Entity
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; } } }