C#資料查詢出來的內容產生實體類

來源:互聯網
上載者:User

以前寫PHP查詢出來都是數組也很容易去迴圈操作,突然用了.NET有點不習慣 不知道該如何去操作。

現在記錄下,利用泛型和反射將資料內容轉化成對應的實體類。

聽說效率很低,這個先不管了。能用就行。

public class Mapping {
public static T Entity<T>(IDataReader reader,Dictionary<string,int> dictionary) {
var type = typeof(T);
//T u = new T();
T u = Activator.CreateInstance<T>();

PropertyInfo[] field = type.GetProperties();
int index = -1;
foreach (var f in field) {
if (dictionary.TryGetValue(f.Name, out index)) {
var r = reader.GetValue(index);
if(r != DBNull.Value)
f.SetValue(u, r, null);
}
}
return u;
}
}

傳入的參數第一個不用解釋了,第二個參數我將代碼貼出來。

Dictionary<string, int> dictionary = new Dictionary<string, int>();

var dr = cmd.ExecuteReader();
int count = dr.FieldCount;
for (int i = 0; i < count; i++) {
dictionary.Add(dr.GetName(i), i);
}

這麼做只是為了方面下面反射的時候從字典中取得對應的屬性名稱和他所對應的鍵。

下面這是完整的查詢並轉化成實體類的代碼

public List<T> findAll<T>() {
var list = new List<T>();
//var parame = new List<QueryParameter>();
//parame.Add("uid");
Dictionary<string, int> dictionary = new Dictionary<string, int>();
using (SqlConnection conn = new SqlConnection(sqlConnectionString)) {
String sql = "SELECT uid,username FROM Users ORDER BY uid DESC";

SqlCommand cmd = new SqlCommand(sql, conn);
//SqlParameter p = new SqlParameter("@uid", 1);
//cmd.Parameters.Add(p);

conn.Open();

var dr = cmd.ExecuteReader();
int count = dr.FieldCount;
for (int i = 0; i < count; i++) {
dictionary.Add(dr.GetName(i), i);
}

while (dr.Read()) {
list.Add(Mapping.Entity<T>(dr,dictionary));
}

dr.Close();
conn.Close();
}
return list;
}

聯繫我們

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