zoukankan      html  css  js  c++  java
  • 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);
    即可。
  • 相关阅读:
    spring boot 整合elasticsearch
    elasticsearch 高级查询
    elasticsearch 基本操作
    day9--回顾
    day9--多线程与多进程
    day9--paramiko模块
    day10--异步IO数据库队列缓存
    数据库连接池
    数据库事务的四大特性以及事务的隔离级别
    使用JDBC进行数据库的事务操作(2)
  • 原文地址:https://www.cnblogs.com/hpbkin/p/10727390.html
Copyright © 2011-2022 走看看