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#實體屬性進行反射


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM