ASP.NET三層架構(gòu)詳解 如何實(shí)現(xiàn)三層架構(gòu)
一、數(shù)據(jù)庫
/*==============================================================*/ /* DBMS name: Microsoft SQL Server 2000 */ /*==============================================================*/ if exists (select 1 from sysobjects where id = object_id('newsContent') and type = 'U') drop table newsContent go /*==============================================================*/ /* Table: newsContent */ /*==============================================================*/ create table newsContent ( ID int identity(1,1) primary key, Title nvarchar(50) not null, Content ntext not null, AddDate datetime not null, CategoryID int not null ) go
二、項(xiàng)目文件架構(gòu)
實(shí)現(xiàn)步驟為:4-3-6-5-2-1
實(shí)現(xiàn)步驟過程
1、創(chuàng)建Model,實(shí)現(xiàn)業(yè)務(wù)實(shí)體。
2、創(chuàng)建IDAL,實(shí)現(xiàn)接口。
3、創(chuàng)建SQLServerDAL,實(shí)現(xiàn)接口里的方法。
4、增加web.config里的配置信息,為SQLServerDAL的程序集。
5、創(chuàng)建DALFactory,返回程序集的指定類的實(shí)例。
6、創(chuàng)建BLL,調(diào)用DALFactory,得到程序集指定類的實(shí)例,完成數(shù)據(jù)操作方法。
7、創(chuàng)建WEB,調(diào)用BLL里的數(shù)據(jù)操作方法。
注意:
1、web.config里的程序集名稱必須與SQLServerDAL里的輸出程序集名稱一致。
2、DALFactory里只需要一個(gè)DataAccess類,可以完成創(chuàng)建所有的程序集實(shí)例。
3、項(xiàng)目創(chuàng)建后,注意修改各項(xiàng)目的默認(rèn)命名空間和程序集名稱。
4、注意修改解決方案里的項(xiàng)目依賴。
5、注意在解決方案里增加各項(xiàng)目引用。
三、各層間的訪問過程
1、傳入值,將值進(jìn)行類型轉(zhuǎn)換(為整型)。
2、創(chuàng)建BLL層的content.cs對(duì)象c,通過對(duì)象c訪問BLL層的方法GetContentInfo(ID)調(diào)用BLL層。
3、BLL層方法GetContentInfo(ID)中取得數(shù)據(jù)訪問層SQLServerDAL的實(shí)例,實(shí)例化IDAL層的接口對(duì)象dal,這個(gè)對(duì)象是由工廠層DALFactory創(chuàng)建的,然后返回IDAL層傳入值所查找的內(nèi)容的方法dal.GetContentInfo(id)。
4、數(shù)據(jù)工廠通過web.config配置文件中給定的webdal字串訪問SQLServerDAL層,返回一個(gè)完整的調(diào)用SQLServerDAL層的路徑給 BLL層。
5、到此要調(diào)用SQLServerDAL層,SQLServerDAL層完成賦值Model層的對(duì)象值為空,給定一個(gè)參數(shù),調(diào)用SQLServerDAL層的SqlHelper的ExecuteReader方法,讀出每個(gè)字段的數(shù)據(jù)賦值給以定義為空的Model層的對(duì)象。
6、SqlHelper執(zhí)行sql命令,返回一個(gè)指定連接的數(shù)據(jù)庫記錄集,在這里需要引用參數(shù)類型,提供為打開連接命令執(zhí)行做好準(zhǔn)備PrepareCommand。
7、返回Model層把查詢得到的一行記錄值賦值給SQLServerDAL層的引入的Model層的對(duì)象ci,然后把這個(gè)對(duì)象返回給BLL。
8、回到Web層的BLL層的方法調(diào)用,把得到的對(duì)象值賦值給Lable標(biāo)簽,在前臺(tái)顯示給界面
四、項(xiàng)目中的文件清單
1、DBUtility項(xiàng)目
(1)connectionInfo.cs
using System; using System.Configuration; namespace Utility { /// <summary> /// ConnectionInfo 的摘要說明。 /// </summary> public class ConnectionInfo { public static string GetSqlServerConnectionString() { return ConfigurationSettings.AppSettings["SQLConnString"]; } } }
2、SQLServerDAL項(xiàng)目
(1)SqlHelper.cs抽象類
using System; using System.Data; using System.Data.SqlClient; using DBUtility; namespace SQLServerDAL { /// <summary> /// SqlHelper 的摘要說明。 /// </summary> public abstract class SqlHelper { public static readonly string CONN_STR = ConnectionInfo.GetSqlServerConnectionString(); /// <summary> /// 用提供的函數(shù),執(zhí)行SQL命令,返回一個(gè)從指定連接的數(shù)據(jù)庫記錄集 /// </summary> /// <remarks> /// 例如: /// SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="connectionString">SqlConnection有效的SQL連接字符串</param> /// <param name="commandType">CommandType:CommandType.Text、CommandType.StoredProcedure</param> /// <param name="commandText">SQL語句或存儲(chǔ)過程</param> /// <param name="commandParameters">SqlParameter[]參數(shù)數(shù)組</param> /// <returns>SqlDataReader:執(zhí)行結(jié)果的記錄集</returns> public static SqlDataReader ExecuteReader(string connString, CommandType cmdType, string cmdText, params SqlParameter[] cmdParms) { SqlCommand cmd = new SqlCommand(); SqlConnection conn = new SqlConnection(connString); // 我們?cè)谶@里用 try/catch 是因?yàn)槿绻@個(gè)方法拋出異常,我們目的是關(guān)閉數(shù)據(jù)庫連接,再拋出異常, // 因?yàn)檫@時(shí)不會(huì)有DataReader存在,此后commandBehaviour.CloseConnection將不會(huì)工作。 try { PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms); SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return rdr; } catch { conn.Close(); throw; } } /// <summary> /// 為執(zhí)行命令做好準(zhǔn)備:打開數(shù)據(jù)庫連接,命令語句,設(shè)置命令類型(SQL語句或存儲(chǔ)過程),函數(shù)語取。 /// </summary> /// <param name="cmd">SqlCommand 組件</param> /// <param name="conn">SqlConnection 組件</param> /// <param name="trans">SqlTransaction 組件,可以為null</param> /// <param name="cmdType">語句類型:CommandType.Text、CommandType.StoredProcedure</param> /// <param name="cmdText">SQL語句,可以為存儲(chǔ)過程</param> /// <param name="cmdParms">SQL參數(shù)數(shù)組</param> private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms) { if (conn.State != ConnectionState.Open) conn.Open(); cmd.Connection = conn; cmd.CommandText = cmdText; if (trans != null) cmd.Transaction = trans; cmd.CommandType = cmdType; if (cmdParms != null) { foreach (SqlParameter parm in cmdParms) cmd.Parameters.Add(parm); } } } }
(2)Content.cs類
using System; using System.Data; using System.Data.SqlClient; using Model; using IDAL; namespace SQLServerDAL { /// <summary> /// Content 的摘要說明。 /// </summary> public class Content:IContent { private const string PARM_ID = "@ID"; private const string SQL_SELECT_CONTENT = "Select ID, Title, Content, AddDate, CategoryID From newsContent Where ID = @ID"; public ContentInfo GetContentInfo(int id) { //創(chuàng)意文章內(nèi)容類 ContentInfo ci = null; //創(chuàng)建一個(gè)參數(shù) SqlParameter parm = new SqlParameter(PARM_ID, SqlDbType.BigInt, 8); //賦上ID值 parm.Value = id; using(SqlDataReader sdr = SqlHelper.ExecuteReader(SqlHelper.CONN_STR, CommandType.Text, SQL_SELECT_CONTENT, parm)) { if(sdr.Read()) { ci = new ContentInfo(sdr.GetInt32(0),sdr.GetString(1), sdr.GetString(2), sdr.GetDateTime(3), sdr.GetInt32(4), sdr.GetInt32(5), sdr.GetString(6)); } } return ci; } } }
3、Model項(xiàng)目
(1)contentInfo.cs
using System; namespace Model { /// <summary> /// Class1 的摘要說明。 /// </summary> public class ContentInfo { private int _ID; private string _Content; private string _Title; private string _From; private DateTime _AddDate; private int _clsID; private int _tmpID; /// <summary> /// 文章內(nèi)容構(gòu)造函數(shù) /// </summary> /// <param name="id">文章流水號(hào)ID</param> /// <param name="content">文章內(nèi)容</param> /// <param name="title">文章標(biāo)題</param> /// <param name="from">文章來源</param> /// <param name="clsid">文章的分類屬性ID</param> /// <param name="tmpid">文章的模板屬性ID</param> public ContentInfo(int id,string title,string content,string from,DateTime addDate,int clsid,int tmpid ) { this._ID = id; this._Content = content; this._Title = title; this._From = from; this._AddDate = addDate; this._clsID = clsid; this._tmpID = tmpid; } //屬性 public int ID { get { return _ID; } } public string Content { get { return _Content; } } public string Title { get { return _Title; } } public string From { get { return _From; } } public DateTime AddDate { get { return _AddDate; } } public int ClsID { get { return _clsID; } } public int TmpID { get { return _tmpID; } } } }
4、IDAL項(xiàng)目
(1)Icontent.cs
using System; using Model; namespace IDAL { /// <summary> /// 文章內(nèi)容操作接口 /// </summary> public interface IContent { /// <summary> /// 取得文章的內(nèi)容。 /// </summary> /// <param name="id">文章的ID</param> /// <returns></returns> ContentInfo GetContentInfo(int id); } }
5、DALFactory項(xiàng)目
(1)Content.cs
using System; using System.Reflection; using System.Configuration; using IDAL; namespace DALFactory { /// <summary> /// 工產(chǎn)模式實(shí)現(xiàn)文章接口。 /// </summary> public class Content { public static IDAL.IContent Create() { // 這里可以查看 DAL 接口類。 string path = System.Configuration.ConfigurationSettings.AppSettings["WebDAL"].ToString(); string className = path+".Content"; // 用配置文件指定的類組合 return (IDAL.IContent)Assembly.Load(path).CreateInstance(className); } } }
6、BLL項(xiàng)目
(1)Content.cs
using System; using Model; using IDAL; namespace BLL { /// <summary> /// Content 的摘要說明。 /// </summary> public class Content { public ContentInfo GetContentInfo(int id) { // 取得從數(shù)據(jù)訪問層取得一個(gè)文章內(nèi)容實(shí)例 IContent dal = DALFactory.Content.Create(); // 用DAL查找文章內(nèi)容 return dal.GetContentInfo(id); } } }
7、Web項(xiàng)目
1)、Web.config:
<appSettings> <add key="SQLConnString" value="Data Source=localhost ;Persist Security info=True;Initial Catalog=newsDB; User ID=sa;Password= " /> <add key="WebDAL" value="SQLServerDAL" /> </appSettings>
2)、WebUI.aspx
<%@ Page language="c#" Codebehind="WebUI.aspx.cs" AutoEventWireup="false" Inherits="Web.WebUI" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML> <HEAD> <title>WebUI</title> <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </HEAD> <body MS_POSITIONING="GridLayout"> <form id="Form1" method="post" runat="server"> <FONT">宋體"></FONT> <table width="600" border="1"> <tr> <td style="WIDTH: 173px"> </td> <td> <asp:Label id="lblTitle" runat="server"></asp:Label></td> </tr> <tr> <td style="WIDTH: 173px; HEIGHT: 22px"> </td> <td style="HEIGHT: 22px"> <asp:Label id="lblDataTime" runat="server"></asp:Label></td> </tr> <tr> <td style="WIDTH: 173px"> </td> <td> <asp:Label id="lblContent" runat="server"></asp:Label></td> </tr> <tr> <td style="WIDTH: 173px"> </td> <td> </td> </tr> <tr> <td style="WIDTH: 173px; HEIGHT: 23px"> </td> <td style="HEIGHT: 23px"> </td> </tr> <tr> <td style="WIDTH: 173px"> </td> <td> </td> </tr> <tr> <td style="WIDTH: 173px"> </td> <td> </td> </tr> <tr> <td style="WIDTH: 173px"> </td> <td> </td> </tr> <tr> <td style="WIDTH: 173px"> </td> <td> <asp:Label id="lblMsg" runat="server">Label</asp:Label></td> </tr> </table> </form> </body> </HTML>
3)、WebUI.aspx.cs后臺(tái)調(diào)用顯示:
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using BLL; using Model; namespace myWeb { /// <summary> /// WebForm1 的摘要說明。 /// </summary> public class WebUI : System.Web.UI.Page { protected System.Web.UI.WebControls.Label lblTitle; protected System.Web.UI.WebControls.Label lblDataTime; protected System.Web.UI.WebControls.Label lblContent; protected System.Web.UI.WebControls.Label lblMsg; private ContentInfo ci ; private void Page_Load(object sender, System.EventArgs e) { if(!Page.IsPostBack) { GetContent("1"); } } private void GetContent(string id) { int ID = WebComponents.CleanString.GetInt(id); Content c = new Content(); ci = c.GetContentInfo(ID); if(ci!=null) { this.lblTitle.Text = ci.Title; this.lblDataTime.Text = ci.AddDate.ToString("yyyy-MM-dd"); this.lblContent.Text = ci.Content; } else { this.lblMsg.Text = "沒有找到這篇文章"; } } #region Web 窗體設(shè)計(jì)器生成的代碼 override protected void OnInit(EventArgs e) { // // CODEGEN: 該調(diào)用是 ASP.NET Web 窗體設(shè)計(jì)器所必需的。 // InitializeComponent(); base.OnInit(e); } /// <summary> /// 設(shè)計(jì)器支持所需的方法 - 不要使用代碼編輯器修改 /// 此方法的內(nèi)容。 /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion } }
4)、WebComponents項(xiàng)目
(1)CleanString.cs
using System; using System.Text; namespace myWeb.WebComponents { /// <summary> /// CleanString 的摘要說明。 /// </summary> public class CleanString { public static int GetInt(string inputString) { try { return Convert.ToInt32(inputString); } catch { return 0; } } public static string InputText(string inputString, int maxLength) { StringBuilder retVal = new StringBuilder(); // check incoming parameters for null or blank string if ((inputString != null) && (inputString != String.Empty)) { inputString = inputString.Trim(); //chop the string incase the client-side max length //fields are bypassed to prevent buffer over-runs if (inputString.Length > maxLength) inputString = inputString.Substring(0, maxLength); //convert some harmful symbols incase the regular //expression validators are changed for (int i = 0; i < inputString.Length; i++) { switch (inputString[i]) { case '"': retVal.Append("""); break; case '<': retVal.Append("<"); break; case '>': retVal.Append(">"); break; default: retVal.Append(inputString[i]); break; } } // Replace single quotes with white space retVal.Replace("'", " "); } return retVal.ToString(); } } }
以上就是ASP.NET三層架構(gòu)的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。
- ASP 使用三層架構(gòu) asp中使用類
- ASP 三層架構(gòu) Error處理類
- ASP 三層架構(gòu) Convert類實(shí)現(xiàn)代碼
- Asp.net 在三層架構(gòu)中事務(wù)的使用實(shí)例代碼
- 基于C#實(shí)現(xiàn)的三層架構(gòu)實(shí)例
- Java Web三層架構(gòu)的配置詳解
- asp.net實(shí)現(xiàn)三層架構(gòu)的例子
- ASP.NET創(chuàng)建三層架構(gòu)圖解詳細(xì)教程
- C# ComboBox的聯(lián)動(dòng)操作(三層架構(gòu))
- ASP.NET存儲(chǔ)過程實(shí)現(xiàn)分頁效果(三層架構(gòu))
相關(guān)文章
ASP.NET用戶注冊(cè)實(shí)戰(zhàn)(第11節(jié))
這篇文章主要介紹了ASP.NET用戶注冊(cè)實(shí)戰(zhàn),鞏固前10小節(jié)所學(xué)的全部知識(shí),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2015-08-08基于ASP.NET+easyUI框架實(shí)現(xiàn)圖片上傳功能(判斷格式+即時(shí)瀏覽 )
這篇文章主要介紹了基于ASP.NET+easyUI框架實(shí)現(xiàn)圖片上傳功能的相關(guān)資料,重點(diǎn)在于如何判斷格式,實(shí)現(xiàn)即時(shí)瀏覽,需要的朋友可以參考下2016-06-06Asp.Net 無刷新文件上傳并顯示進(jìn)度條的實(shí)現(xiàn)方法及思路
這篇文章詳細(xì)介紹了無刷新文件上傳并顯示進(jìn)度條的思路和代碼,有需要的朋友可以參考一下2013-06-06如何在 .NET 中使用 Flurl 高效處理Http請(qǐng)求
這篇文章主要介紹了如何在 .NET 中使用 Flurl 高效處理Http請(qǐng)求,幫助大家更好的理解和學(xué)習(xí)使用.net技術(shù),感興趣的朋友可以了解下2021-05-05ASP.NET Core讀取Request.Body的正確方法
相信大家在使用ASP.NET Core進(jìn)行開發(fā)的時(shí)候,肯定會(huì)涉及到讀取Request.Body的場景,畢竟我們大部分的POST請(qǐng)求都是將數(shù)據(jù)存放到Http的Body當(dāng)中,本文就介紹一下ASP.NET Core讀取Request.Body,感興趣的可以了解一下2021-05-05