這篇文章討論如何在c#中實現3層架構,使用MS Access數據庫存儲數據。在此,我在3層架構中實現一個小型的可復用的組件保存客戶數據。并提供添加,更新,查找客戶數據的功能。
背景
首先,我介紹一些3層架構的理論知識。簡單說明:什么是3層架構?3層架構的優點是什么?
什么是3層架構?
3層架構是一種“客戶端-服務器”架構,在此架構中用戶接口,商業邏輯,數據保存以及數據訪問被設計為獨立的模塊。主要有3個層面,第一層(表現層,GUI層),第二層(商業對象,商業邏輯層),第三層(數據訪問層)。這些層可以單獨開發,單獨測試。
為什么要把程序代碼分為3層。把用戶接口層,商業邏輯層,數據訪問層分離有許多的優點。
在快速開發中重用商業邏輯組件,我們已經在系統中實現添加,更新,刪除,查找客戶數據的組件。這個組件已經開發并且測試通過,我們可以在其他要保存客戶數據的項目中使用這個組件。
系統比較容易遷移,商業邏輯層與數據訪問層是分離的,修改數據訪問層不會影響到商業邏輯層。系統如果從用SQL Server存儲數據遷移到用Oracle存儲數據,并不需要修改商業邏輯層組件和GUI組件
系統容易修改,假如在商業層有一個小小的修改,我們不需要在用戶的機器上重裝整個系統。我們只需要更新商業邏輯組件就可以了。
應用程序開發人員可以并行,獨立的開發單獨的層。
代碼
這個組件有3層,第一個層或者稱為GUI層用form實現,叫做FrmGUI。第二層或者稱為商業邏輯層,叫做BOCustomer,是Bussniess Object Customer的縮寫。最后是第三層或者稱為數據層,叫做DACustomer,是Data Access Customer的縮寫。為了方便,我把三個層編譯到一個項目中。
用戶接口層
下面是用戶接口成的一段代碼,我只選取了調用商業邏輯層的一部分代碼。
//This function get the details from the user via GUI
//tier and calls the Add method of business logic layer.
private void cmdAdd_Click(object sender, System.EventArgs e)
{
try
{
cus = new BOCustomer();
cus.cusID=txtID.Text.ToString();
cus.LName = txtLName.Text.ToString();
cus.FName = txtFName.Text.ToString();
cus.Tel= txtTel.Text.ToString();
cus.Address = txtAddress.Text.ToString();
cus.Add();
}
catch(Exception err)
{
MessageBox.Show(err.Message.ToString());
}
}
//This function gets the ID from the user and finds the
//customer details and return the details in the form of
//a dataset via busniss object layer. Then it loops through
//the content of the dataset and fills the controls.
private void cmdFind_Click(object sender, System.EventArgs e)
{
try
{
String cusID = txtID.Text.ToString();
BOCustomer thisCus = new BOCustomer();
DataSet ds = thisCus.Find(cusID);
DataRow row;
row = ds.Tables[0].Rows[0];
//via looping
foreach(DataRow rows in ds.Tables[0].Rows )
{
txtFName.Text = rows["CUS_F_NAME"].ToString();
txtLName.Text = rows["CUS_L_NAME"].ToString();
txtAddress.Text = rows["CUS_ADDRESS"].ToString();
txtTel.Text = rows["CUS_TEL"].ToString();
}
}
catch (Exception err)
{
MessageBox.Show(err.Message.ToString());
}
}
//this function used to update the customer details.
private void cmdUpdate_Click(object sender, System.EventArgs e)
{
try
{
cus = new BOCustomer();
cus.cusID=txtID.Text.ToString();
cus.LName = txtLName.Text.ToString();
cus.FName = txtFName.Text.ToString();
cus.Tel= txtTel.Text.ToString();
cus.Address = txtAddress.Text.ToString();
cus.Update();
}
catch(Exception err)
{
MessageBox.Show(err.Message.ToString());
}
}
NET技術:在C#中實現3層架構,轉載需保留來源!
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。