.net中如何給資料表實體類賦值的方法

來源:互聯網
上載者:User
資料

今天遇到一個問題,就是資料實體類中如何給屬性賦值.因為從資料庫中取出來的是一個DataSet如果一個一個給資料實體類中的屬性賦值顯的非常的笨拙,而且我們的資料表多達24個.在網上搜尋了下寫出了個簡單的方法,代碼如下:

首先我們做個實體類

 1     public class Class1
 2     {
 3         private int inttemp;
 4
 5         public int IntTemp
 6         {
 7             get { return inttemp; }
 8             set { inttemp = value; }
 9         }
10     }
11

那我們怎麼找到他並賦值呢?

代碼如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 using System.Reflection;
 5 using System.Data;
 6
 7 namespace ConsoleApplication1
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             Class1 c = new Class1();
14 /*這裡是構造一個DataSet*/
15             DataSet ds = new DataSet();
16             DataTable dt = new DataTable();
17             dt.Columns.Add("IntTemp",SqlDbType.Int.GetType());
18             DataRow dr = dt.NewRow();
19             dr["IntTemp"] = 2;
20             dt.Rows.Add(dr);
21             ds.Tables.Add(dt);
22
23 /*這裡是重點*/
24             foreach (DataRow dr1 in ds.Tables[0].Rows)
25             {
26                 foreach (DataColumn dc in dr1.Table.Columns)
27                 {
28                     PropertyInfo pi = c.GetType().GetProperty(dc.ColumnName);//擷取根據表的類名建立的實體類屬性
29                     pi.SetValue(c, dc.Table.Rows[0][0], null);//設定這個屬性的值
30                 }
31             }
32             Console.Write(c.IntTemp+"\n");
33         }
34     }
35
36 }
 
大家可能問這個有什麼用?當你按照資料庫表的形式簡曆了一個實體類就可以用這個迴圈寫一個共有的方法專門給不同的實體類的屬性賦值,因為pi.SetValue方法的第一個值是object形式的.這樣我們就少了很多的麻煩事情.

不知道這個方法對多資料集是否有效率的問題.高手們看了後給我點意見修改下.謝謝了.



聯繫我們

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