ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2021-04-26 18:55:29  阅读:196  来源: 互联网

标签:实体类 var dt typeof 集合 model null DataTable


 

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
{    /// 
    /// DataTable转list泛型集合    
    /// 
    public static class DataTableExtend
    {        /// 
        /// DataTable转换List        /// 
        /// 泛型
        /// DataTable
        /// List泛型集合
        public static ListToList(this DataTable dt) where T : class, new()
        {            var list = new List();            foreach (DataRow dr in dt.Rows)
            {                //泛型对象
                T model = dr.ToDataRowModel();
                list.Add(model);
            }            return list;
        }        /// 
        /// DataSet转换List        /// 
        /// 泛型
        /// DataTable
        /// List泛型集合
        public static ListToList(this DataSet ds) where T : class, new()
        {            var list = new List();
            list = ds.Tables[0].ToList();            return list;
        }        /// 
        /// DataRow转换T模型        /// 
        /// 泛型
        /// DataTable
        /// List泛型集合
        public static T ToDataRowModel(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

        /// 
        ///     实体列表转换成DataTable        /// 
        /// 实体
        ///  实体列表
        /// 
        public static DataTable EntityListToDataTable(this IList 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

        /// 
        ///     实体转换成DataTable        ///     Add by loki 20201011        /// 
        /// 实体
        /// 
        public static DataTable EntityToDataTable(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#实体属性进行反射


标签:实体类,var,dt,typeof,集合,model,null,DataTable
来源: https://blog.51cto.com/u_15078738/2735142

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有