C# DataTable 转 实体类

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

比如:List<RtmInterview> rtmList = GetDataById( id);

public List<RtmInterview> GetDataById(string id)
        {
            List<RtmInterview> rtmList = new List<RtmInterview>();
            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<RtmInterview>().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<RtmInterviewStep> steplist = new DatatableToEntity<RtmInterviewStep>().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 DatatableToEntity<T> where T : new()
    {
        /// <summary>
        /// 填充对象列表:用DataSet的第一个表填充实体类
        /// </summary>
        /// <param name="ds">DataSet</param>
        /// <returns></returns>
        public List<T> FillModel(DataSet ds)
        {
            if (ds == null || ds.Tables[0] == null || ds.Tables[0].Rows.Count == 0)
            {
                return null;
            }
            else
            {
                return FillModel(ds.Tables[0]);
            }
        }

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

        /// <summary>  
        /// 填充对象列表:用DataTable填充实体类
        /// </summary>  
        public List<T> FillModel(DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return null;
            }
            List<T> modelList = new List<T>();
            foreach (DataRow dr in dt.Rows)
            {
                //T model = (T)Activator.CreateInstance(typeof(T));  
                T model = new T();
                for (int i = 0; i < dr.Table.Columns.Count; 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;
        }

        /// <summary>  
        /// 填充对象:用DataRow填充实体类
        /// </summary>  
        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 < dr.Table.Columns.Count; 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);
即可。

猜你喜欢

转载自www.cnblogs.com/hpbkin/p/10727390.html
今日推荐