[轉]C#反射,根據反射將資料庫查詢資料和實體類綁定,並未實體類賦值

來源:互聯網
上載者:User

標籤:sch   www   log   ram   bnu   tac   手動   dbn   自訂   

本文來自:http://www.cnblogs.com/mrchenzh/archive/2010/05/31/1747937.html

/*****************************************
* 說明:利用反射將資料庫查詢的內容自動綁定
*       到實體類
*
* 時間:1:49 2009-9-19
*
* 程式員:王文壯
* ***************************************/
/****************資料庫指令碼***************
* create database MySchool
* go
* use MySchool
* go
* create table Student
* (
* ID int identity primary key,
* Name varchar(10)
* )
* ****************************************/
using System;
using System.Reflection;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;

namespace ReflectionDemo
{
    #region Main
    class Program
    {
        static void Main(string[] args)
        {
            DataSet ds = new DataSet();

            #region 串連資料庫構建DataSet

            //SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=MySchool;Integrated Security=True");
            //SqlDataAdapter objAdapter = new SqlDataAdapter("Select * from student", con);
            //objAdapter.Fill(ds);

            #endregion

            #region 手動構建DataSet

            DataTable dt = new DataTable();
            dt.Columns.Add("ID");
            dt.Columns.Add("Name");
            DataRow row = dt.NewRow();
            row["ID"] = 1;
            row["Name"] = "灰太狼";
            dt.Rows.Add(row);
            ds.Tables.Add(dt);
            #endregion

            List<Student> students = new List<Student>();
            foreach (DataRow dataRow in ds.Tables[0].Rows)
            {
                Student stu = new Student();
                Utility.ConvertToEntity(stu, row);
                students.Add(stu);
            }
            foreach (Student student in students)
            {
                Console.WriteLine(student.Name);
            }
        }
    }
    #endregion

    #region 實體類

    /// <summary>
    /// 實體類,需要在屬性
    /// 上添加自訂特性
    /// 每個實體類對應資料表裡
    /// 的一個欄位,注意,自訂特性裡的參數
    /// 一定要和資料表裡的欄位一一對應,
    /// 否則就反射不到了!
    /// </summary>
    public class Student
    {
        [DataContextAttribute("ID")]
        public int ID { get; set; }
        [DataContext("Name")]
        public string Name { get; set; }
    }

    #endregion

    #region 自訂特性

    /// <summary>
    /// 自訂特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Property)]
    public class DataContextAttribute : Attribute
    {
        /// <summary>
        /// 自訂特性
        /// </summary>
        /// <param name="fieldName">資料表欄位名稱</param>
        public DataContextAttribute(string property) { this.Property = property; }
        /// <summary>
        /// 資料表欄位屬性(實體屬性)
        /// </summary>
        public string Property { get; set; }
    }

    #endregion

    #region 反射

    public class Utility
    {
        /// <summary>
        /// 將DataRow轉換成實體
        /// </summary>
        /// <param name="obj">實體</param>
        /// <param name="row">資料表一行資料</param>
        public static void ConvertToEntity(object obj, DataRow row)
        {
            ///得到obj的類型
            Type type = obj.GetType();
            ///返回這個類型的所有公用屬性
            PropertyInfo[] infos = type.GetProperties();
            ///迴圈公用屬性數組
            foreach (PropertyInfo info in infos)
            {
                ///返回自訂屬性數組
                object[] attributes = info.GetCustomAttributes(typeof(DataContextAttribute), false);
                ///將自訂屬性數組迴圈
                foreach (DataContextAttribute attribute in attributes)
                {
                    ///如果DataRow裡也包括此列
                    if (row.Table.Columns.Contains(attribute.Property))
                    {
                        ///將DataRow指定列的值賦給value
                        object value = row[attribute.Property];
                        ///如果value為null則返回
                        if (value == DBNull.Value) continue;
                        ///將值做轉換
                        if (info.PropertyType.Equals(typeof(string)))
                        {
                            value = row[attribute.Property].ToString();
                        }
                        else if (info.PropertyType.Equals(typeof(int)))
                        {
                            value = Convert.ToInt32(row[attribute.Property]);
                        }
                        else if (info.PropertyType.Equals(typeof(decimal)))
                        {
                            value = Convert.ToDecimal(row[attribute.Property]);
                        }
                        else if (info.PropertyType.Equals(typeof(DateTime)))
                        {
                            value = Convert.ToDateTime(row[attribute.Property]);
                        }
                        else if (info.PropertyType.Equals(typeof(double)))
                        {
                            value = Convert.ToDouble(row[attribute.Property]);
                        }
                        else if (info.PropertyType.Equals(typeof(bool)))
                        {
                            value = Convert.ToBoolean(row[attribute.Property]);
                        }
                        ///利用反射自動將value賦值給obj的相應公用屬性
                        info.SetValue(obj, value, null);
                    }
                }
            }
        }
    }

    #endregion
}

[轉]C#反射,根據反射將資料庫查詢資料和實體類綁定,並未實體類賦值

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.