C# DataTable 转 实体类

2021-06-07 23:04

阅读:361

标签:column   index   大写   add   time   opera   忽略   datetime   pes   

C# 中查询结果DataTable转实体类:

比如:List rtmList = GetDataById( id);

public List GetDataById(string id)
        {
            List rtmList = new List();
            bool ConnectionOpenHere = false;
            try
            {
                DataTable dt = new DataTable();
                if (this.command.Connection.State == System.Data.ConnectionState.Closed) { this.command.Connection.Open(); ConnectionOpenHere = true; }
                string strsql = string.Format("select a.*,b.depname from RTM_INTERVIEW a left join rtm_dept b on (a.depid=b.id) where upper(a.id)=‘{0}‘", id);
                this.command.CommandText = strsql;
                this.dataAdapter.Fill(dt);

                rtmList = new DatatableToEntity().FillModel(dt);

                dt.Clear();
                this.command.CommandText = string.Format("select * from RTM_INTERVIEW_APPROVE where upper(interviewid)=‘{0}‘ order by createon desc",id);
                this.dataAdapter.Fill(dt);
                List steplist = new DatatableToEntity().FillModel(dt);
                rtmList.ForEach(s=>s.ApproveSteps=steplist);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            finally
            {
                if (ConnectionOpenHere) { this.command.Connection.Close(); }
            }
            return rtmList;

        }

其中:DatatableToEntity 类如下:

using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text;

namespace HRData.RTM.NewOperate
{
    public class DatatableToEntitywhere T : new()
    {
        /// 
        /// 填充对象列表:用DataSet的第一个表填充实体类
        /// 
        /// DataSet
        /// 
        public List FillModel(DataSet ds)
        {
            if (ds == null || ds.Tables[0] == null || ds.Tables[0].Rows.Count == 0)
            {
                return null;
            }
            else
            {
                return FillModel(ds.Tables[0]);
            }
        }

        // 
        /// 填充对象列表:用DataSet的第index个表填充实体类
        ///   
        public List FillModel(DataSet ds, int index)
        {
            if (ds == null || ds.Tables.Count 0)
            {
                return null;
            }
            else
            {
                return FillModel(ds.Tables[index]);
            }
        }

        ///   
        /// 填充对象列表:用DataTable填充实体类
        ///   
        public List FillModel(DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return null;
            }
            List modelList = new List();
            foreach (DataRow dr in dt.Rows)
            {
                //T model = (T)Activator.CreateInstance(typeof(T));  
                T model = new T();
                for (int i = 0; i )
                {
                    PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                    if (propertyInfo != null && dr[i] != DBNull.Value)
                    {
                        string value = dr[i] == null ? "" : dr[i].ToString();
                        //string typestr = dr[i].GetType().Name;
                        //if(typestr.Equals("DateTime"))
                            //value = dr[i].ToString();
                        propertyInfo.SetValue(model, value, null);
                    }
                        
                }

                modelList.Add(model);
            }
            return modelList;
        }

        ///   
        /// 填充对象:用DataRow填充实体类
        ///   
        public T FillModel(DataRow dr)
        {
            if (dr == null)
            {
                return default(T);
            }

            //T model = (T)Activator.CreateInstance(typeof(T));  
            T model = new T();

            for (int i = 0; i )
            {
                PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                if (propertyInfo != null && dr[i] != DBNull.Value)
                {
                    string value = dr[i] == null ? "" : dr[i].ToString();
                    //string typestr = dr[i].GetType().Name;
                    //if(typestr.Equals("DateTime"))
                    //value = dr[i].ToString();
                    propertyInfo.SetValue(model, value, null);
                }
            }
            return model;
        }

    }
}

注意: 忽略大小写的方法,比如数据库字段都是大写,但是实体类是C#骆驼峰式或其他写法时不匹配。

所以修改  

PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
即可。

C# DataTable 转 实体类

标签:column   index   大写   add   time   opera   忽略   datetime   pes   

原文地址:https://www.cnblogs.com/hpbkin/p/10727390.html


评论


亲,登录后才可以留言!