通過反射動態實填充實體類

來源:互聯網
上載者:User

第一種:檢測整個實體類

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;
using System.Data;

public partial class bangsotest_dr : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        IList<user> userlist;
        string sqlcmd = "select top 1000 Username,Password from userinfo order by id";//這裡的Username和Password會根據實體類中的對應欄位,自動填滿或跳過
        using (SqlDataReader dr = Bangso.DBUtility.SQLHelper.ExecuteDataReader(sqlcmd))
        {
            userlist = FillEntityFromReader<user>(dr);
        }

        foreach (user u in userlist)
        {
            Response.Write(u.Username + "<br>");
        }
    }

    public static IList<T> FillEntityFromReader<T>(SqlDataReader reader)
    {
        List<T> list = new List<T>();
        List<PropertyInfo> pinfoList = new List<PropertyInfo>();
        Boolean checkedPropertyInfo = false;
        while (reader.Read())
        {
            T instance = Activator.CreateInstance<T>();

            #region 檢查資料庫欄位與實體類屬性的匹配情況
            if (!checkedPropertyInfo)
            {
                foreach (PropertyInfo pinfo in typeof(T).GetProperties())
                {
                    //判斷reader是否有此Property中的BoundFieldAttribute所對應需要綁定的欄位
                    if (reader.GetSchemaTable().Select("ColumnName='" + pinfo.Name + "'").Length > 0)
                    {
                        pinfoList.Add(pinfo);
                    }
                }
            }
            #endregion

            //查檢完成
            checkedPropertyInfo = true;

            //開始賦值
            foreach (PropertyInfo info in pinfoList)
            {
                int index = reader.GetOrdinal(info.Name);
                if (reader.GetValue(index) != DBNull.Value)
                {
                    if (!info.PropertyType.IsEnum)
                    {
                        info.SetValue(instance, Convert.ChangeType(reader.GetValue(index), info.PropertyType), null);
                    }
                    else
                    {
                        info.SetValue(instance, Enum.Parse(info.PropertyType, reader.GetValue(index).ToString()), null);
                    }
                }
            }

            list.Add(instance);
        }
        reader.Close();
        return list;
    }

    public class user
    {
        string username;
        public string Username
        {
            get { return username; }
            set { username = value; }
        }
    }
}

 第二種根據實體類中的特性來選擇填充哪些屬性

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;

public partial class bangsotest_dr : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        IList<user> userlist;
        string sqlcmd = "select top 100 username from userinfo";
        using (SqlDataReader dr = Bangso.DBUtility.SQLHelper.ExecuteDataReader(sqlcmd))
        {
            userlist = FillEntityFromReader<user>(dr);
        }

        foreach (user ui in userlist)
        {
            Response.Write(ui.Username + "<br>");
        }
    }

    public static IList<T> FillEntityFromReader<T>(SqlDataReader reader)
    {
        List<T> list = new List<T>();
        List<PropertyInfo> pinfoList = new List<PropertyInfo>();
        Boolean checkedPropertyInfo = false;
        while (reader.Read())
        {
            T instance = Activator.CreateInstance<T>();            #region 檢查資料庫欄位與實體類屬性的匹配情況

            if (!checkedPropertyInfo)
            {
                foreach (PropertyInfo pinfo in typeof(T).GetProperties())
                {
                    foreach (BoundFieldAttribute attr in pinfo.GetCustomAttributes(typeof(BoundFieldAttribute), true))
                    {
                        //判斷reader是否有此Property中的BoundFieldAttribute所對應需要綁定的欄位
                        if (reader.GetSchemaTable().Select("ColumnName='" + attr.FieldName + "'").Length > 0)
                        {
                            pinfoList.Add(pinfo);
                        }
                    }
                }
            }
            #endregion

            //查檢完成
            checkedPropertyInfo = true;

            //開始賦值
            foreach (PropertyInfo info in pinfoList)
            {
                int index = reader.GetOrdinal(info.Name);
                if (reader.GetValue(index) != DBNull.Value)
                {
                    if (!info.PropertyType.IsEnum)
                    {
                        info.SetValue(instance, Convert.ChangeType(reader.GetValue(index), info.PropertyType), null);
                    }
                    else
                    {
                        info.SetValue(instance, Enum.Parse(info.PropertyType, reader.GetValue(index).ToString()), null);
                    }
                }
            }

            list.Add(instance);
        }
        return list;
    }

    public class BoundFieldAttribute : Attribute
    {
        private string fieldName;

        /// <summary>
        /// 指定繫結資料庫欄位名
        /// </summary>
        public string FieldName
        {
            get { return fieldName; }
        }

        /// <summary>
        /// 初始化一個特性
        /// </summary>
        /// <param name="_fieldName">資料庫欄位名</param>
        public BoundFieldAttribute(string _fieldName)
        {
            this.fieldName = _fieldName;
        }
    }

    public class user
    {
        string username, password;
        [BoundFieldAttribute("Username")]//這裡的特性聲明一定要,否則將無法綁定
        public string Username
        {
            get { return username; }
            set { username = value; }
        }
        
        public string Password//這裡的Password將不會被填充,因為它沒有聲明特性
        {
            get { return password; }
            set { password = value; }
        }
    }
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.