码迷,mamicode.com
首页 > Windows程序 > 详细

C# DataTable 转 实体类

时间:2019-04-18 09:33:50      阅读:152      评论:0      收藏:0      [点我收藏+]

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

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);
即可。

C# DataTable 转 实体类

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

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!