程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> DataReader,DataTable利用泛型填充實體類

DataReader,DataTable利用泛型填充實體類

編輯:C#入門知識

 

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
  
/// <summary>  
///TestTableModel 的摘要說明  
/// </summary>  
public class TestTableModel  
{  
    public int D_Id { get; set; }  
    public string D_Name { get; set; }  
    public string D_Password { get; set; }  
    public string D_Else { get; set; }  
    public decimal D_Amount { get; set; }  
}  

   
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Data;  
using System.Reflection;  
  
namespace MSCL  
{  
    /// <summary>  
    ///ObjectToList 的摘要說明  
    /// </summary>  
    public static class ObjectToList  
    {  
        /*  --示例 
            IDataReader dr = MSCL.SqlHelper.GetSqlDataReader("select * from TestTable where d_id in(6,7,8)"); 
            List<TestTableModel> t1 = MSCL.ObjectToList.DataReaderToList<TestTableModel>(dr); 
            for (int i = 0; i < t1.Count; i++) 
            { 
                Response.Write(t1[i].D_Id + "<br/>"); 
                Response.Write(t1[i].D_Name + "<br/>"); 
                Response.Write(t1[i].D_Password + "<br/>"); 
                Response.Write(t1[i].D_Else + "<br/>"); 
                Response.Write(t1[i].D_Amount + "<br/>"); 
            }    
            dr.Dispose(); 
            dr.Close(); 
         */  
  
        /// <summary>  
        /// DataReader利用泛型填充實體類  
        /// </summary>  
        /// <typeparam name="T">實體類</typeparam>  
        /// <param name="reader">DataReader</param>  
        /// <returns></returns>  
        public static List<T> DataReaderToList<T>(IDataReader reader)  
        {  
            //實例化一個List<>泛型集合  
            List<T> DataList = new List<T>();  
            while (reader.Read())  
            {  
                T RowInstance = Activator.CreateInstance<T>();//動態創建數據實體對象  
                //通過反射取得對象所有的Property  
                foreach (PropertyInfo Property in typeof(T).GetProperties())  
                {  
                    try  
                    {  
                        //取得當前數據庫字段的順序  
                        int Ordinal = reader.GetOrdinal(Property.Name);  
                        if (reader.GetValue(Ordinal) != DBNull.Value)  
                        {  
                            //將DataReader讀取出來的數據填充到對象實體的屬性裡  
                            Property.SetValue(RowInstance, Convert.ChangeType(reader.GetValue(Ordinal), Property.PropertyType), null);  
                        }  
                    }  
                    catch  
                    {  
                        break;  
                    }  
                }  
                DataList.Add(RowInstance);  
            }  
            return DataList;  
        }  
  
        /// <summary>  
        /// DataTable利用泛型填充實體類  
        /// </summary>  
        /// <typeparam name="T">實體類</typeparam>  
        /// <param name="dt">DataTable</param>  
        /// <returns></returns>  
        public static List<T> DataTableToList<T>(DataTable dt) where T : new()  
        {  
            var list = new List<T>();  
            if (dt == null) return list;  
            var len = dt.Rows.Count;  
  
            for (var i = 0; i < len; i++)  
            {  
                var info = new T();  
                foreach (DataColumn dc in dt.Rows[i].Table.Columns)  
                {  
                    var field = dc.ColumnName;  
                    var value = dt.Rows[i][field].ToString();  
                    if (string.IsNullOrEmpty(value)) continue;  
                    if (IsDate(value))  
                    {  
                        value = DateTime.Parse(value).ToString();  
                    }  
  
                    var p = info.GetType().GetProperty(field);  
  
                    try  
                    {  
                        if (p.PropertyType == typeof(string))  
                        {  
                            p.SetValue(info, value, null);  
                        }  
                        else if (p.PropertyType == typeof(int))  
                        {  
                            p.SetValue(info, int.Parse(value), null);  
                        }  
                        else if (p.PropertyType == typeof(bool))  
                        {  
                            p.SetValue(info, bool.Parse(value), null);  
                        }  
                        else if (p.PropertyType == typeof(DateTime))  
                        {  
                            p.SetValue(info, DateTime.Parse(value), null);  
                        }  
                        else if (p.PropertyType == typeof(float))  
                        {  
                            p.SetValue(info, float.Parse(value), null);  
                        }  
                        else if (p.PropertyType == typeof(double))  
                        {  
                            p.SetValue(info, double.Parse(value), null);  
                        }  
                        else  
                        {  
                            p.SetValue(info, value, null);  
                        }  
                    }  
                    catch (Exception)  
                    {  
                        //p.SetValue(info, ex.Message, null);   
                    }  
                }  
                list.Add(info);  
            }  
            dt.Dispose(); dt = null;  
            return list;  
        }  
  
        /// <summary>  
        /// 是否是時間  
        /// </summary>  
        /// <param name="d"></param>  
        /// <returns></returns>  
        private static bool IsDate(string d)  
        {  
            DateTime d1;  
            double d2;  
            return !double.TryParse(d, out d2) && DateTime.TryParse(d, out d1);  
        }  
    }  
}  

 

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved