• C# DataTable DataSet DataRow 转实体类集合,实体类和实体类集合转成DataTable 扩展方法分享


    代码越写越灵活,分享越分享越快乐

    C# DataTable  DataSet  DataRow 转实体类集合,实体类和实体类集合转成DataTable 扩展方法分享

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Reflection;
    
    namespace System
    {
        /// <summary>
        /// DataTable转list泛型集合    
        /// </summary>
        public static class DataTableExtend
        {
            /// <summary>
            /// DataTable转换List
            /// </summary>
            /// <typeparam name="T">泛型</typeparam>
            /// <param name="dt">DataTable</param>
            /// <returns>List泛型集合</returns>
            public static List<T> ToList<T>(this DataTable dt) where T : class, new()
            {
                var list = new List<T>();
                foreach (DataRow dr in dt.Rows)
                {
                    //泛型对象
                    T model = dr.ToDataRowModel<T>();
                    list.Add(model);
                }
                return list;
            }
    
            /// <summary>
            /// DataSet转换List
            /// </summary>
            /// <typeparam name="T">泛型</typeparam>
            /// <param name="dt">DataTable</param>
            /// <returns>List泛型集合</returns>
            public static List<T> ToList<T>(this DataSet ds) where T : class, new()
            {
                var list = new List<T>();
                list = ds.Tables[0].ToList<T>();
                return list;
            }
    
            /// <summary>
            /// DataRow转换T模型
            /// </summary>
            /// <typeparam name="T">泛型</typeparam>
            /// <param name="dt">DataTable</param>
            /// <returns>List泛型集合</returns>
            public static T ToDataRowModel<T>(this DataRow dr) where T : class, new()
            {
                //泛型对象
                T model = new T();
                //属性集合
                var listPro = model.GetType().GetProperties().Where(item => !item.IsDefined(typeof(InternalAttribute), false)).ToArray();
                foreach (PropertyInfo pi in listPro)
                {
                    var columnName = pi.Name;//属性=字段
                    var columnType = pi.PropertyType;//属性类型
                    var underlyingtype = Nullable.GetUnderlyingType(columnType);//返回指定可以为null值的类型
    
                    //判断属性是否可以写入
                    if (!pi.CanWrite) continue;
                    if (!dr.Table.Columns.Contains(columnName)) continue;
                    var value = dr[columnName];
                    //判断字段值是否为空
                    if (value == DBNull.Value) continue;
                    //根据属性类型转换数据库字段类型
                    if (columnType == typeof(string))
                        pi.SetValue(model, value.ToString(), null);
                    else if (columnType == typeof(int) || columnType == typeof(int?))
                        pi.SetValue(model, Convert.ToInt32(value), null);
                    else if (columnType == typeof(DateTime) || columnType == typeof(DateTime?))
                        pi.SetValue(model, Convert.ToDateTime(value), null);
                    else if (columnType == typeof(decimal))
                        pi.SetValue(model, Convert.ToDecimal(value), null);
                    else if (columnType == typeof(double))
                        pi.SetValue(model, Convert.ToDouble(value), null);
                    else if (columnType == typeof(float))
                        pi.SetValue(model, Convert.ToSingle(value), null);
                    else if ((underlyingtype ?? columnType).IsEnum)
                    {
                        if (underlyingtype != null && !string.IsNullOrEmpty(value.ToString()))
                            pi.SetValue(model, Enum.Parse(underlyingtype ?? columnType, value.ToString()), null);
                        else if (underlyingtype == null && !string.IsNullOrEmpty(value.ToString()))
                            pi.SetValue(model, Convert.ToInt32(value), null);
                        else
                            pi.SetValue(model, -1, null);
                    }
                    else
                        pi.SetValue(model, value, null);
                }
                return model;
            }
        }
    }

     实体列表转换成DataTable

            /// <summary>
            ///     实体列表转换成DataTable
            /// </summary>
            /// <typeparam name="TEntity">实体</typeparam>
            /// <param name="entityList"> 实体列表</param>
            /// <returns></returns>
            public static DataTable EntityListToDataTable<TEntity>(this IList<TEntity> entityList)
                where TEntity : class
            {
                if (entityList == null) return null;
                var dt = new DataTable(typeof(TEntity).Name);
    
                var myPropertyInfo = typeof(TEntity).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    
                #region 创建表结构
    
                foreach (var property in myPropertyInfo)
                {                
                    Type colType = property.PropertyType;
                    if (colType.IsGenericType && colType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    {
                        colType = colType.GetGenericArguments()[0];
                        var col = new DataColumn(property.Name, colType) { Caption = property.ToDescription() };
                        col.AllowDBNull = true;
                        dt.Columns.Add(col);
                    }
                    else
                    {
                        var col = new DataColumn(property.Name, colType) { Caption = property.ToDescription() };
                        dt.Columns.Add(col);
                    }
                       
                }
    
                #endregion
    
                foreach (var entity in entityList)
                {
                    if (entity == null) continue;
    
                    var row = dt.NewRow();
                    foreach (var propertyInfo in myPropertyInfo)
                    {
                        if (propertyInfo.GetValue(entity, null) == null)
                            row[propertyInfo.Name] = DBNull.Value;
                        else
                            row[propertyInfo.Name] = propertyInfo.GetValue(entity, null);
                    }
    
                    dt.Rows.Add(row);
                }
    
                return dt;
            }

    实体转换成DataTable

            /// <summary>
            ///     实体转换成DataTable
            ///     Add by loki 20201011
            /// </summary>
            /// <typeparam name="TEntity">实体</typeparam>
            /// <returns></returns>
            public static DataTable EntityToDataTable<TEntity>(this TEntity entity)
                where TEntity : class
            {
                if (entity == null) return null;
                var dt = new DataTable(typeof(TEntity).Name);
    
                var myPropertyInfo = typeof(TEntity).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    
                #region 创建表结构
    
                foreach (var property in myPropertyInfo)
                {                
                    Type colType = property.PropertyType;
                    if (colType.IsGenericType && colType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    {
                        colType = colType.GetGenericArguments()[0];
                        var col = new DataColumn(property.Name, colType) { Caption = property.ToDescription() };
                        col.AllowDBNull = true;
                        dt.Columns.Add(col);
                    }
                    else
                    {
                        var col = new DataColumn(property.Name, colType) { Caption = property.ToDescription() };
                        dt.Columns.Add(col);
                    }
    
                }
    
                #endregion
                var row = dt.NewRow();
                foreach (var propertyInfo in myPropertyInfo)
                {
                    if (propertyInfo.GetValue(entity, null) == null)
                        row[propertyInfo.Name] = DBNull.Value;
                    else
                        row[propertyInfo.Name] = propertyInfo.GetValue(entity, null);
                }
    
                dt.Rows.Add(row);
    
                return dt;
            }

    你如果觉得有用就拿去不用谢!C# DataTable  DataSet  DataRow 转实体类集合,实体类和实体类集合转成DataTable 扩展方法分享,这里其实很简单,就是用到反射技术去实现的,将数据库表字段与C#实体属性进行反射

  • 相关阅读:
    行转列问题
    Session对象失效的客户端解决方法
    Spring之依赖注入
    Spring开发入门
    非关系型数据库redis
    Json(JavaScript Object Notation)
    Ajax
    JavaScript框架之JQuery
    Web核心之Filter过滤器
    Web核心练习之分页模块和条件模块(后台代码为主,jsp已经落伍)
  • 原文地址:https://www.cnblogs.com/axinno1/p/12896202.html
Copyright © 2020-2023  润新知