[C#.NET][ADO.NET] 類別(Data Transfer Object )與資料繫結

  • 12877
  • 0
  • 2013-07-05

[C#.NET][ADO.NET] 類別(Data Transfer Object )與資料繫結

常用的資料繫結應該就是ADO.NET家族中的Datatable跟DataSet了,塞進去DataRow的資料都會變成object(boxing),要取出時還得用轉型(unboxing),Boxing and Unboxing (C# Programming Guide),效能似乎沒有那麼好,除了ADO.NET家族成員之外,使用類別來進去資料傳遞也是相當不錯的選擇。

 

我先建立一個Member類別,然後建立MemberList類別,MemberList類別只是用來收集Member的成員而已,BindingList<>類別使用起來的效能比List<>類別效能好,所以我用它來處理集合。

public class MemberList
{
    private BindingList<Member> _MemberCollection = null;
    public BindingList<Member> MemberCollection
    {
        get
        {
            if (this._MemberCollection == null)
                this._MemberCollection = new BindingList<Member>();
            return this._MemberCollection;
        } 

    }
}
public class Member
{
    public int? ID { get; set; }
    public string Name { get; set; }
    public int? Age { get; set; }
    public string Phone { get; set; }
}

 

 

 

 

接下來,塞一些資料給集合

public MemberList CreateClass()
{
    MemberList list = new MemberList();
    list.MemberCollection.Add(new Member() { ID = 1, Name = "余小章", Age = 18, Phone = "000" });
    list.MemberCollection.Add(new Member() { ID = 2, Name = "王小華", Age = 28, Phone = "001" });
    list.MemberCollection.Add(new Member() { ID = 3, Name = "張小明", Age = 20, Phone = "002" });
    return list;
}

 

然後我將資料丟到BindingSource.DataSource 屬性,當然也可以丟到dataGridView1.DataSource 屬性,我習慣統一由BindingSource管理,您可依照自己的需求更改。

BindingSource _Source = new BindingSource();
public void Form1_Load(object sender, EventArgs e)
{
    this._Source.DataSource = CreateClass().MemberCollection; 

    this.dataGridView1.DataSource = this._Source;
    this.bindingNavigator1.BindingSource = this._Source;
    this.textBox1.DataBindings.Add("Text", this._Source, "ID");
    this.textBox2.DataBindings.Add("Text", this._Source, "Name");
    this.textBox3.DataBindings.Add("Text", this._Source, "Age");
    this.textBox4.DataBindings.Add("Text", this._Source, "Phone");
}

 

 

 

 

image

 

後記:

1.DataSource屬性的資料來源可以是實作下列其中一個介面的任何型別:http://msdn.microsoft.com/zh-tw/library/system.windows.forms.datagridview.datasource.aspx

 

2.DTO這名詞是昨天第一次從朱大那邊聽來的,原來使用類別來傳遞資料還有專有名詞,自己用了那麼久了還不曉得,Data Transfer Object使用心得及時機

3.敲資料對應表我想是麻煩的一件事,只要稍不留神就敲錯了,Pete介紹使用AutoMapper可以很輕鬆的進行資料對應,使用AutoMapper簡化Data Transfer Object與Business Entity的對應程式碼

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo