• 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;
            }
        }
    }
  • 相关阅读:
    centos6 python 安装 sqlite 解决 No module named ‘_sqlite3′
    Python--Virtualenv简明教程
    【centos】 error: command 'gcc' failed with exit status 1
    python3.5学习笔记:linux6.4 安装python3 pip setuptools
    Python的虚拟环境virtualenv
    hdu Robberies
    转载:hdu 动态规划题集
    在Eclipse中配置Tomcat 创建和运行Servlet/JSP
    opengl中层次建模的实现
    shiyan2
  • 原文地址:https://www.cnblogs.com/fanqisoft/p/11671428.html
Copyright © 2020-2023  润新知