基于C#實現(xiàn)的三層架構實例
本文所述為基于C#實現(xiàn)的三層架構。對于三層的概念查相信大家并不陌生,這里舉一個關于三層的簡單實例,真正看一下它是如何具體實現(xiàn)的.
我們先來一起看看實體類-Model
實質:實體類就是在完成數(shù)據(jù)庫與實體類對應的功能,一個類是一張表,一個屬性是一個字段!
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace model { public class User { public User() { } private string _name; public string name { set { _name = value; } get { return _name; } } } }
再來說明一下,這個實例應用了配置文件來訪問數(shù)據(jù)庫,當然我們在做的時候可以使用SqlHelper,也可以將連接數(shù)據(jù)庫的這些代碼直接放在D層
<add name="ConnectionString" connectionString="Data Source=localhost;Initial Catalog=tester;User ID=sa;Password=123456" providerName="System.Data.SqlClient" />
三層中的最底層-數(shù)據(jù)訪問層(DAL) 這一層要引用實體類和對Configuration的引用
實質:就是對數(shù)據(jù)庫中的內(nèi)容的增,刪,改,查
using System; using System.Collections.Generic; using System.Linq; using System.Text; using model; using System.Data; using System.Configuration; using System.Data.SqlClient; namespace DAL { public class UserDB { public bool User_add(model.User model) { string setting = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString(); SqlConnection myconn=new SqlConnection(setting); myconn.Open(); SqlCommand cmd=new SqlCommand("insert into dbo.[user]([name]) values(@name)",myconn); cmd.Parameters.AddWithValue("@name", model.name); if (cmd.ExecuteNonQuery()>0) { return true; } else { return false; } } } }
三層中的橋梁-業(yè)務邏輯層BLL 這一層需要引用實體類和數(shù)據(jù)訪問層
實質:負責處理U層的問題(本例子主要是對數(shù)據(jù)層的操作)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DAL; namespace BLL { public class userBLL { DAL.UserDB db = new UserDB(); public bool addUser(model.User model) { return db.User_add(model); } } }
三層中的頂層-表現(xiàn)層UI 這一層要引用實體類和業(yè)務邏輯層
實質:具體解決做什么的問題
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using BLL; using model; namespace 登陸 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { model.User thisUser = new User(); thisUser.name = TB_username.Text.ToString(); BLL.userBLL uB = new userBLL(); if (uB.addUser (thisUser)) { MessageBox.Show ("true"); } else { MessageBox.Show ("false"); } } } }
三層之間的關系如下圖所示:
解釋:
上述代碼中DAL主要是對數(shù)據(jù)庫中的內(nèi)容的操作,在這里就是向數(shù)據(jù)庫中添加用戶。BLL則主要是調用DAL層的操作,返回DAL層添加用戶的結果(true或者false)。這樣也就是在客戶端與數(shù)據(jù)庫中加了一個中間層,使得兩層的依賴性減小。UI層則主要完成響應用戶的需求,去調用BLL層實現(xiàn)的adduser方法,DAL層就是實實在在做這件事情的操作。
相關文章
WPF利用WindowChrome實現(xiàn)自定義窗口
這篇文章主要為大家詳細介紹了WPF如何利用WindowChrome實現(xiàn)自定義窗口,文中的示例代碼講解詳細,具有一定的借鑒價值,需要的可以參考一下2023-02-02深入多線程之:內(nèi)存柵欄與volatile關鍵字的使用分析
本篇文章對內(nèi)存柵欄與volatile關鍵字的使用進行了詳細的分析介紹,需要的朋友參考下2013-05-05將DataTable轉換成List<T>實現(xiàn)思路及示例代碼
首先,這是我寫的一個通用轉換類,完成此類操作。也是實現(xiàn)這個功能最核心的部分。需要的朋友可以過來參考下,希望對大家有所幫助2013-11-11