zoukankan      html  css  js  c++  java
  • 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;
            }
        }
    }
  • 相关阅读:
    golang GC(二 定位)
    MySQL的安装与配置——详细教程
    js实现关闭浏览器
    解决mysql:ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO/YES)
    如何将将本地电脑部署成服务器
    Mysql统计每年每个月的数据——详细教程
    博客、笔记
    JAVAWEB实现修改功能
    JAVAWEB实现添加功能
    JavaWeb实现删除功能
  • 原文地址:https://www.cnblogs.com/fanqisoft/p/11671428.html
Copyright © 2011-2022 走看看