asp.net一个带抽象工厂的三层架构完整实例

本文不是原创,根据http://www.cnblogs.com/cresuccess/archive/2008/12/10/1351675.html改编,实现了增删改查、返回数据功能。在vs2010+sql2008Express下实现。

本实例主要完成对一个newsTable表的更删改查操作,包括DBUtility、Model、IDAL、SQLServerDAL、DALFactoty、BLL和一个Web网站共7个项目。建立后的截图。

一、数据库

 

/*==============================================================*/
/* DBMS name: Microsoft SQL Server 2008 */
/*==============================================================*/


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 varchar(100) not null,
Contents varchar(1000) not null,
AddDate datetime not null,)
go

 

二、项目文件架构

实现步骤为:4-3-6-5-2-1

ID

项目

描述

用途

项目引用关系

实例所需文件

相关方法

1

Web

表现层

Web页和控件

引用BLL

WebUI.aspx

WebUI.aspx.cs

GetContent()

2

BLL

业务逻辑层

业务逻辑组件

引用 IDAL,Model,使用DALFactory创建实例

Content.cs

ContentInfo   GetContentInfo(int id)

3

IDAL

数据访问层接口定义

每个DAL实现都要实现的一组接口

引用 Model

IContent.cs

ContentInfo   GetContentInfo(int id)

4

Model

业务实体

传递各种数据的容器

无引用

ContentInfo.cs

 

5

DALFactory

数据层的抽象工厂

创建反射,用来确定加载哪一个数据库访问程序集的类

引用IDAL,通过读取web.config里设置的程序集,加载类的实例,返回给BLL使用。

Content.cs

IDAL.Icontent   create()

6

SQLServerDAL

SQLServer数据访问层

Microsoft   SQL Server特定的Pet   Shop DAL实现,使用了IDAL接口

引用 Model和IDAL,被DALFactory加载的程序集,实现接口里的方法。

SqlHelper.cs

Content.cs

SqlDataReader   ExecuteReader()

PrepareCommand()

ContentInfo   GetContentInfo(int id)

OracleDAL

Oracle数据访问层

7

DBUtility

数据库访问组件基础类

微软的经典PETSHOP中的SQLHELPER,这个是可有可无的,也可以自己定义一个,

无引用

 

 

实现步骤过程

1、创建Model,实现业务实体。

2、创建IDAL,实现接口。

3、创建SQLServerDAL,实现接口里的方法。

4、增加web.config里的配置信息,为SQLServerDAL的程序集。

5、创建DALFactory,返回程序集的指定类的实例。

6、创建BLL,调用DALFactory,得到程序集指定类的实例,完成数据操作方法。

7、创建WEB,调用BLL里的数据操作方法。

注意:

1、web.config里的程序集名称必须与SQLServerDAL里的输出程序集名称一致。

2、DALFactory里只需要一个DataAccess类,可以完成创建所有的程序集实例。

3、项目创建后,注意修改各项目的默认命名空间和程序集名称。

4、注意修改解决方案里的项目依赖。

5、注意在解决方案里增加各项目引用。

三、各层间的访问过程

1、传入值,将值进行类型转换(为整型)。

2、创建BLL层的content.cs对象c,通过对象c访问BLL层的方法GetContentInfo(ID)调用BLL层。

3、BLL层方法GetContentInfo(ID)中取得数据访问层SQLServerDAL的实例,实例化IDAL层的接口对象dal,这个对象是由工厂层DALFactory创建的,然后返回IDAL层传入值所查找的内容的方法dal.GetContentInfo(id)。

4、数据工厂通过web.config配置文件中给定的webdal字串访问SQLServerDAL层,返回一个完整的调用SQLServerDAL层的路径给 BLL层。

5、到此要调用SQLServerDAL层,SQLServerDAL层完成赋值Model层的对象值为空,给定一个参数,调用SQLServerDAL层的SqlHelper的ExecuteReader方法,读出每个字段的数据赋值给以定义为空的Model层的对象。

6、SqlHelper执行sql命令,返回一个指定连接的数据库记录集,在这里需要引用参数类型,提供为打开连接命令执行做好准备PrepareCommand。

7、返回Model层把查询得到的一行记录值赋值给SQLServerDAL层的引入的Model层的对象ci,然后把这个对象返回给BLL。

8、回到Web层的BLL层的方法调用,把得到的对象值赋值给Lable标签,在前台显示给界面

四、文件源程序

1、DBUtility项目

SQLHelper.cs  引用 System.Configuration命名空间

using System;

using System.Configuration;

using System.Data;

using System.Data.SqlClient;

using System.Collections;

using System.Configuration;

 

namespace DBUtility

 

{

 

    /// <summary>

    /// SqlHelper类¤¨¤是º?专Á¡§门?提¬¨¢供?给?广?大䨮用®?户¡ì用®?于®¨²高?性?能¨¹、¡é可¨¦升¦y级?和¨ª最Á?佳?练¢¡¤习¡ã的Ì?sql数ºy据Y操¨´作Á¡Â

    /// </summary>

    public abstract class SqlHelper {

 

        //数ºy据Y库a连¢?接¨®字Á?符¤?串ä?

        public static readonly string sConnetinString = ConfigurationManager.ConnectionStrings["newsConnectionString"].ConnectionString;

           

        // 用®?于®¨²缓o存ä?参?数ºy的Ì?HASH表À¨ª

        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());

 

        /// <summary>

        ///  给?定¡§连¢?接¨®的Ì?数ºy据Y库a用®?假¨´设¦¨¨参?数ºy执¡ä行D一°?个?sql命¨¹令¢?(ꡧ不?返¤¦Ì回?数ºy据Y集¡¥)ê?

        /// </summary>

        /// <param name="connectionString">一°?个?有®D效¡ì的Ì?连¢?接¨®字Á?符¤?串ä?</param>

        /// <param name="commandType">命¨¹令¢?类¤¨¤型¨ª(存ä?储ä¡é过y程¨¬, 文?本À?, 等̨¨等̨¨)</param>

        /// <param name="commandText">存ä?储ä¡é过y程¨¬名?称?或¨°者?sql命¨¹令¢?语®?句?</param>

        /// <param name="commandParameters">执¡ä行D命¨¹令¢?所¨´用®?参?数ºy的Ì?集¡¥合?</param>

        /// <returns>执¡ä行D命¨¹令¢?所¨´影®¡ã响¨¬的Ì?行D数ºy</returns>

        public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {

 

            SqlCommand cmd = new SqlCommand();

 

            using (SqlConnection conn = new SqlConnection(connectionString)) {

                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);

                int val = cmd.ExecuteNonQuery();

                cmd.Parameters.Clear();

                return val;

            }

        }

 

        /// <summary>

        /// 用®?现?有®D的Ì?数ºy据Y库a连¢?接¨®执¡ä行D一°?个?sql命¨¹令¢?(ꡧ不?返¤¦Ì回?数ºy据Y集¡¥)ê?

        /// </summary>

        /// <param name="conn">一°?个?现?有®D的Ì?数ºy据Y库a连¢?接¨®</param>

        /// <param name="commandType">命¨¹令¢?类¤¨¤型¨ª(存ä?储ä¡é过y程¨¬, 文?本À?, 等̨¨等̨¨)</param>

        /// <param name="commandText">存ä?储ä¡é过y程¨¬名?称?或¨°者?sql命¨¹令¢?语®?句?</param>

        /// <param name="commandParameters">执¡ä行D命¨¹令¢?所¨´用®?参?数ºy的Ì?集¡¥合?</param>

        /// <returns>执¡ä行D命¨¹令¢?所¨´影®¡ã响¨¬的Ì?行D数ºy</returns>

        public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {

 

            SqlCommand cmd = new SqlCommand();

 

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);

            int val = cmd.ExecuteNonQuery();

            cmd.Parameters.Clear();

            return val;

        }

 

        /// <summary>

        ///使º1用®?现?有®D的Ì?SQL事º?务?执¡ä行D一°?个?sql命¨¹令¢?(ꡧ不?返¤¦Ì回?数ºy据Y集¡¥)ê?

        /// </summary>

        /// <remarks>

        ///举¨´例¤y: 

        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));

        /// </remarks>

        /// <param name="trans">一°?个?现?有®D的Ì?事º?务?</param>

        /// <param name="commandType">命¨¹令¢?类¤¨¤型¨ª(存ä?储ä¡é过y程¨¬, 文?本À?, 等̨¨等̨¨)</param>

        /// <param name="commandText">存ä?储ä¡é过y程¨¬名?称?或¨°者?sql命¨¹令¢?语®?句?</param>

        /// <param name="commandParameters">执¡ä行D命¨¹令¢?所¨´用®?参?数ºy的Ì?集¡¥合?</param>

        /// <returns>执¡ä行D命¨¹令¢?所¨´影®¡ã响¨¬的Ì?行D数ºy</returns>

        public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {

            SqlCommand cmd = new SqlCommand();

            PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);

            int val = cmd.ExecuteNonQuery();

            cmd.Parameters.Clear();

            return val;

        }

 

        /// <summary>

        /// 用®?执¡ä行D的Ì?数ºy据Y库a连¢?接¨®执¡ä行D一°?个?返¤¦Ì回?数ºy据Y集¡¥的Ì?sql命¨¹令¢?

        /// </summary>

        /// <remarks>

        /// 举¨´例¤y: 

        ///  SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));

        /// </remarks>

        /// <param name="connectionString">一°?个?有®D效¡ì的Ì?连¢?接¨®字Á?符¤?串ä?</param>

        /// <param name="commandType">命¨¹令¢?类¤¨¤型¨ª(存ä?储ä¡é过y程¨¬, 文?本À?, 等̨¨等̨¨)</param>

        /// <param name="commandText">存ä?储ä¡é过y程¨¬名?称?或¨°者?sql命¨¹令¢?语®?句?</param>

        /// <param name="commandParameters">执¡ä行D命¨¹令¢?所¨´用®?参?数ºy的Ì?集¡¥合?</param>

        /// <returns>包㨹含?结¨¢果?的Ì?读¨¢取¨?器¡Â</returns>

        public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)

        {

            //创ä¡ä建¡§一°?个?SqlCommand对?象¨®

            SqlCommand cmd = new SqlCommand();

            //创ä¡ä建¡§一°?个?SqlConnection对?象¨®

            SqlConnection conn = new SqlConnection(connectionString);

 

            //在¨²这a里¤?我¨°们?用®?一°?个?try/catch结¨¢构1执¡ä行Dsql文?本À?命¨¹令¢?/存ä?储ä¡é过y程¨¬,ê?因°¨°为a如¨?果?这a个?方¤?法¤¡§产¨²生¦¨²一°?个?异°¨¬常¡ê我¨°们?要°a关?闭À?连¢?接¨®,ê?因°¨°为a没?有®D读¨¢取¨?器¡Â存ä?在¨²,ê?

            //因°¨°此ä?commandBehaviour.CloseConnection 就¨ª不?会¨¢执¡ä行D

            try {

                //调Ì¡Â用®? PrepareCommand 方¤?法¤¡§,ê?对? SqlCommand 对?象¨®设¦¨¨置?参?数ºy

                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);

                //调Ì¡Â用®? SqlCommand  的Ì? ExecuteReader 方¤?法¤¡§

                SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                //清?除y参?数ºy

                cmd.Parameters.Clear();

                return reader;

            }

            catch {

                //关?闭À?连¢?接¨®,ê?抛¡Á出?异°¨¬常¡ê

                conn.Close();

                throw;

            }

        }

 

        /// <summary>

        /// 用®?指?定¡§的Ì?数ºy据Y库a连¢?接¨®字Á?符¤?串ä?执¡ä行D一°?个?命¨¹令¢?并¡é返¤¦Ì回?一°?个?数ºy据Y集¡¥的Ì?第̨²一°?列¢D

        /// </summary>

        /// <remarks>

        ///例¤y如¨?: 

        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));

        /// </remarks>

        ///<param name="connectionString">一°?个?有®D效¡ì的Ì?连¢?接¨®字Á?符¤?串ä?</param>

        /// <param name="commandType">命¨¹令¢?类¤¨¤型¨ª(存ä?储ä¡é过y程¨¬, 文?本À?, 等̨¨等̨¨)</param>

        /// <param name="commandText">存ä?储ä¡é过y程¨¬名?称?或¨°者?sql命¨¹令¢?语®?句?</param>

        /// <param name="commandParameters">执¡ä行D命¨¹令¢?所¨´用®?参?数ºy的Ì?集¡¥合?</param>

        /// <returns>用®? Convert.To{Type}把ã?类¤¨¤型¨ª转Áa换?为a想?要°a的Ì? </returns>

        public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {

            SqlCommand cmd = new SqlCommand();

 

            using (SqlConnection connection = new SqlConnection(connectionString)) {

                PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);

                object val = cmd.ExecuteScalar();

                cmd.Parameters.Clear();

                return val;

            }

        }

 

        /// <summary>

        /// 用®?指?定¡§的Ì?数ºy据Y库a连¢?接¨®执¡ä行D一°?个?命¨¹令¢?并¡é返¤¦Ì回?一°?个?数ºy据Y集¡¥的Ì?第̨²一°?列¢D

        /// </summary>

        /// <remarks>

        /// 例¤y如¨?: 

        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));

        /// </remarks>

        /// <param name="conn">一°?个?存ä?在¨²的Ì?数ºy据Y库a连¢?接¨®</param>

        /// <param name="commandType">命¨¹令¢?类¤¨¤型¨ª(存ä?储ä¡é过y程¨¬, 文?本À?, 等̨¨等̨¨)</param>

        /// <param name="commandText">存ä?储ä¡é过y程¨¬名?称?或¨°者?sql命¨¹令¢?语®?句?</param>

        /// <param name="commandParameters">执¡ä行D命¨¹令¢?所¨´用®?参?数ºy的Ì?集¡¥合?</param>

        /// <returns>用®? Convert.To{Type}把ã?类¤¨¤型¨ª转Áa换?为a想?要°a的Ì? </returns>

        public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {

 

            SqlCommand cmd = new SqlCommand();

 

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);

            object val = cmd.ExecuteScalar();

            cmd.Parameters.Clear();

            return val;

        }

 

        /// <summary>

        /// 将?参?数ºy集¡¥合?添¬¨ª加¨®到Ì?缓o存ä?

        /// </summary>

        /// <param name="cacheKey">添¬¨ª加¨®到Ì?缓o存ä?的Ì?变À?量¢?</param>

        /// <param name="cmdParms">一°?个?将?要°a添¬¨ª加¨®到Ì?缓o存ä?的Ì?sql参?数ºy集¡¥合?</param>

        public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)

        {

            parmCache[cacheKey] = commandParameters;

        }

 

        /// <summary>

        /// 找¨°会¨¢缓o存ä?参?数ºy集¡¥合?

        /// </summary>

        /// <param name="cacheKey">用®?于®¨²找¨°回?参?数ºy的Ì?关?键¨¹字Á?</param>

        /// <returns>缓o存ä?的Ì?参?数ºy集¡¥合?</returns>

        public static SqlParameter[] GetCachedParameters(string cacheKey) {

            SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];

 

            if (cachedParms == null)

                return null;

 

            SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];

 

            for (int i = 0, j = cachedParms.Length; i < j; i++)

                clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();

 

            return clonedParms;

        }

 

        /// <summary>

        /// 准Á?备À?执¡ä行D一°?个?命¨¹令¢?

        /// </summary>

        /// <param name="cmd">sql命¨¹令¢?</param>

        /// <param name="conn">Sql连¢?接¨®</param>

        /// <param name="trans">Sql事º?务?</param>

        /// <param name="cmdType">命¨¹令¢?类¤¨¤型¨ª例¤y如¨? 存ä?储ä¡é过y程¨¬或¨°者?文?本À?</param>

        /// <param name="cmdText">命¨¹令¢?文?本À?,例¤y如¨?:êoSelect * from Products</param>

        /// <param name="cmdParms">执¡ä行D命¨¹令¢?的Ì?参?数ºy</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);

            }

        }

    }

}

 

 

 

二、Model项目  对象-关系模型转换。

ContentInfo.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace Model //定¡§义°?实º¦Ì体¬?类¤¨¤

{

    public class ContentInfo

    {

        private int _ID;

        private string _Title;

        private string _Contents;

        private DateTime _AddDate;

      /// <summary>

      /// 文?章?内¨²容¨Y构1造¨¬函¡¥数ºy

      /// </summary>

      /// <param name="id">文?章?流¢¡Â水?号?ID</param>

      /// <param name="title">文?章?标À¨º题¬a</param>

      /// <param name="contents">文?章?内¨²容¨Y</param>

      /// <param name="addDate">发¤¡é表À¨ª日¨?期¨²</param>

       

        public ContentInfo(int id, string title, string contents,DateTime addDate)

        {

            this._ID = id;

            this._Title = title;

            this._Contents = contents;

            this._AddDate = addDate;

          

 

        }

        public ContentInfo()

        { }

        //属º?性?

        public int ID

        {

            get { return _ID; }

            set { _ID = value; }

        }

        public string Title

        {

            get { return _Title; }

            set { _Title = value; }

        }

        public string Contents

        {

            get { return _Contents; }

            set { _Contents = value; }

        }

    

        public DateTime AddDate

        {

            get { return _AddDate; }

            set { _AddDate = value; }

        }

  

    

    }

}

 

三、IDAL 项目

IContent.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Model;

 

namespace IDAL //定¡§义°?接¨®口¨²,ê?主¡Â要°a是º?要°a完ª¨º成¨¦的Ì?操¨´作Á¡Â

{

   /// <summary>

   /// 文?章?内¨²容¨Y操¨´作Á¡Â接¨®口¨²

   /// </summary>

    public interface IContent

    {

       /// <summary>

       /// 取¨?得Ì?文?章?的Ì?内¨²容¨Y

       /// </summary>

       /// <param name="id">文?章?的Ì?ID</param>

       /// <returns></returns>

       int AddContentInfo(ContentInfo Content);

       int DeleteContentInfo(int id);

       int UpdateContentInfo(ContentInfo Content);

       List<ContentInfo> SelectContentInfo(int id);

       List<ContentInfo> GetAllContentInfo();

    }

}

 

四、SQLSERVERDAL项目

Content.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Model;

using IDAL;

using System.Data;

using System.Data.SqlClient;

using DBUtility;

 

namespace SQLServerDAL

{

      public class Content : IContent

        {

          public  int AddContentInfo(ContentInfo Content)

          {

             SqlParameter[] parm=new SqlParameter[]

             {

                  new SqlParameter("@Title",SqlDbType.VarChar,100),

                  new SqlParameter("@Contents",SqlDbType.VarChar,1000),

                  new SqlParameter("@AddDate",SqlDbType.DateTime,8),

               };

              parm[0].Value=Content.Title;

              parm[1].Value=Content.Contents;

              parm[2].Value=Content.AddDate;

            string sSql="insert into newsContent (Title,Contents,AddDate) values (@Title,@Contents,@AddDate);";

            return (SqlHelper.ExecuteNonQuery(SqlHelper.sConnetinString, CommandType.Text, sSql, parm));

 

          }

 

           public   int DeleteContentInfo(int id)

           {

               SqlParameter parm = new SqlParameter("@ID",SqlDbType.Int,32);

               parm.Value = id;

               string sSql = "delete newsContent where ID=@ID;";

               return (SqlHelper.ExecuteNonQuery(SqlHelper.sConnetinString,CommandType.Text,sSql,parm));

 

           }

           public  int UpdateContentInfo(ContentInfo Content)

            {

                SqlParameter[] parm = new SqlParameter[]

                  {

                     new SqlParameter("@ID",SqlDbType.Int,32),

                     new SqlParameter("@Title",SqlDbType.VarChar,100),

                     new SqlParameter("@Contents",SqlDbType.VarChar,1000),

                     new SqlParameter("@AddDate",SqlDbType.DateTime,8),//DateTime是º?8位?的Ì?。¡ê

                  };

                parm[0].Value = Content.ID;

                parm[1].Value = Content.Title;

                parm[2].Value = Content.Contents;

                parm[3].Value = Content.AddDate;

               string sSql = "update newsContent set Title=@Title,Contents=@Contents,AddDate=@AddDate where ID=@ID;";

                return(SqlHelper.ExecuteNonQuery(SqlHelper.sConnetinString,CommandType.Text,sSql,parm));

             

            }

          public  List<ContentInfo> SelectContentInfo(int id)

            {

               List<ContentInfo> listConent=new List<ContentInfo>();

               SqlParameter parm = new SqlParameter("@ID",SqlDbType.Int,32);

               parm.Value = id;

               string sSql="select *  from newsContent where ID=@ID ";

 

               using (SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.sConnetinString, CommandType.Text, sSql, parm))

               {

                   while (dr.Read())

                   {

                       listConent.Add( new ContentInfo(dr.GetInt32(0), dr.GetString(1), dr.GetString(2), dr.GetDateTime(3)));

                   }

                   return listConent;

               }

            }

          public    List<ContentInfo> GetAllContentInfo()

            {

                List<ContentInfo> listConent = new List<ContentInfo>();

                string sSql = "select *  from newsContent";

                using (SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.sConnetinString, CommandType.Text, sSql, null))

                {

                    while (dr.Read())

                    {

                        listConent.Add(new ContentInfo(dr.GetInt32(0), dr.GetString(1), dr.GetString(2), dr.GetDateTime(3)));

                    }

                    return listConent;

                }

            }

 

        

        }

  

}

 

 

五、DALFactory项目

Content.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using IDAL;

using System.Reflection; //使用反射,读取Web配置文件,创建一种数据库对象的实例。

using System.Configuration;

 

namespace DALFactory

{

 

    public class Content

    {

 

        public static IDAL.IContent Create()

        {

            string path = ConfigurationManager.AppSettings["WebDAL"].ToString();

            string className = path + ".Content";

            //有®D配?置?文?件t指?定¡§的Ì?类¤¨¤组Á¨¦合?。¡ê

            return (IDAL.IContent)Assembly.Load(path).CreateInstance(className);

        }

    }

}

 

六、BLL项目 调用工厂类,返回抽象接口

Content.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Model;

using IDAL;

using DALFactory;

 

 

namespace BLL

{

    public class Content

    {

       Private dal=  IContent dal = DALFactory.Content.Create();

 

        public int AddContentInfo(ContentInfo Content)

        {

            return dal.AddContentInfo(Content);

        }

        public int DeleteContentInfo(int id)

        {

            return dal.DeleteContentInfo(id);

 

        }

        public int UpdateContentInfo(ContentInfo Content)

        {

            return dal.UpdateContentInfo(Content);

           

        }

        public List<ContentInfo> SelectContentInfo(int id)

        {

            return dal.SelectContentInfo(id);

        }

        public List<ContentInfo> GetAllContentInfo()

        {

             return dal.GetAllContentInfo();

        }

    }

}

 

 

七、WEB层(网站或Web应用程序)

Web.config

<?xml version="1.0"?>

<!--

  有®D关?如¨?何?配?置? ASP.NET 应®|用®?程¨¬序¨°的Ì?详¨º细?信?息¡é,ê?请?访¤?问¨º

  http://go.microsoft.com/fwlink/?LinkId=169433

  -->

<configuration>

         <system.web>

                  <compilation debug="true" targetFramework="4.0"/>

         </system.web>

         <connectionStrings>

                  <add name="newsConnectionString" connectionString="Data Source=.\sqlexpress;Initial Catalog=dbNews;Integrated Security=True;Pooling=False"/>

         </connectionStrings>

         <appSettings>

                  <add key="WebDAL" value="SQLServerDAL"/>

         </appSettings>

</configuration>

 

Default.aspx前台

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:Localize ID="Localize1" runat="server">标À¨º题¬a:</asp:Localize>

        <asp:TextBox ID="tb_Title" runat="server"></asp:TextBox><br />

        <asp:Localize ID="Localize2"  runat="server">内¨²容¨Y:êo</asp:Localize>

        <asp:TextBox ID="tb_Contents" runat="server" TextMode="MultiLine"  Height="154px" Width="215px"></asp:TextBox>

        <br />

       &nbsp;&nbsp; <asp:Button ID="btn_Send" runat="server" Text="发¤¡é表À¨ª"

            onclick="btn_Send_Click" />&nbsp;

        <input id="Reset1" type="reset"   value="清?空?" />

 

        <asp:GridView ID="gv_NewsContent" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"

            AllowPaging="True" CellPadding="4" ForeColor="#333333" GridLines="None"

            onrowdatabound="gv_NewsContent_RowDataBound"

            onpageindexchanging="gv_NewsContent_PageIndexChanging"

            onrowcancelingedit="gv_NewsContent_RowCancelingEdit"

            onrowdeleting="gv_NewsContent_RowDeleting"

            onrowediting="gv_NewsContent_RowEditing"

            onrowupdating="gv_NewsContent_RowUpdating" PageSize="5" ShowFooter="True"

            Width="915px" >

            <AlternatingRowStyle BackColor="White" />

            <Columns>

                <asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />

                <asp:TemplateField HeaderText="标À¨º题¬a" SortExpression="Title" ItemStyle-Width="200px">

                    <EditItemTemplate>

                        <asp:TextBox ID="tb_Title" runat="server" Text='<%# Bind("Title") %>'></asp:TextBox>

                    </EditItemTemplate>

                    <ItemTemplate>

                        <asp:Label ID="lb_Title" runat="server" Text='<%# Bind("Title") %>'></asp:Label>

                    </ItemTemplate>

                    <FooterTemplate>

                     <asp:Label ID="lb_RecordNumber" runat="server" Text=""></asp:Label>

                    </FooterTemplate>

                </asp:TemplateField>

                <asp:TemplateField HeaderText="内¨²容¨Y" SortExpression="Contents" ItemStyle-Width="400px">

                    <EditItemTemplate>

                        <asp:TextBox ID="tb_Contents" runat="server" Text='<%# Bind("Contents") %>'></asp:TextBox>

                    </EditItemTemplate>

                    <ItemTemplate>

                        <asp:Label ID="lb_Contents" runat="server" Text='<%# Bind("Contents") %>'></asp:Label>

                    </ItemTemplate>

                    <FooterTemplate >

                        <asp:Label ID="lb_PageCount" runat="server" Text=""></asp:Label>

                    </FooterTemplate>

                </asp:TemplateField>

                <asp:TemplateField HeaderText="发¤¡é表À¨ª时º¡À间?">

                    <EditItemTemplate>

                        <asp:TextBox ID="tb_AddDate" runat="server" Text='<%# Bind("AddDate") %>'></asp:TextBox>

                    </EditItemTemplate>

                    <ItemTemplate>

                        <asp:Label ID="lb_AddDate" runat="server" Text='<%# Bind("AddDate") %>'></asp:Label>

                    </ItemTemplate>

                </asp:TemplateField>

                <asp:CommandField ShowEditButton="True" />

                <asp:CommandField ShowDeleteButton="True" />

            </Columns>

            <EditRowStyle BackColor="#2461BF" />

            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

            <PagerSettings FirstPageText="首º¡Á页°3" LastPageText="末?页°3"

                Mode="NextPreviousFirstLast" NextPageText="下?一°?页°3" PreviousPageText="上¦?一°?页°3" />

            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />

            <RowStyle BackColor="#EFF3FB" />

            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />

            <SortedAscendingCellStyle BackColor="#F5F7FB" />

            <SortedAscendingHeaderStyle BackColor="#6D95E1" />

            <SortedDescendingCellStyle BackColor="#E9EBEF" />

            <SortedDescendingHeaderStyle BackColor="#4870BE" />

        </asp:GridView>

    </div>

    </form>

</body>

</html>

 

后台:Default.aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using Model;

using BLL;

 

public partial class _Default : System.Web.UI.Page

{

    int TotalRowsCount = 0;

    private BLL.Content ct = new BLL.Content();

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            SetBind();

        }

    }

 

    private void SetBind()

    {

        gv_NewsContent.DataSource = ct.GetAllContentInfo();

        TotalRowsCount= ct.GetAllContentInfo().Count;

        //TotalRowsCount = gv_NewsContent.Rows.Count; 在¨²分¤?页?状Á¡ä态¬?下?不?能¨¹使º1用®?GridView 的Ì?Rows.Count来¤¡ä获?取¨?总Á¨¹记?录?数ºy,ê?它¨¹只?是º?获?得Ì?当Ì¡À前¡ã页°3面?的Ì?记?录?数ºy

        gv_NewsContent.DataBind();

   

    }

    protected void btn_Send_Click(object sender, EventArgs e)

    {

        Model.ContentInfo ci = new ContentInfo();

        ci.Title = tb_Title.Text;

        ci.Contents = tb_Contents.Text;

        ci.AddDate = DateTime.Now;

        ct.AddContentInfo(ci);

        SetBind();

    }

    protected void gv_NewsContent_RowDataBound(object sender, GridViewRowEventArgs e)

    {

        if (e.Row.RowType == DataControlRowType.DataRow)

        {

            e.Row.Attributes.Add("onmouseover", "currentcolor=this.style.backgroundColor;this.style.backgroundColor='lightblue'");//鼠º¨®标À¨º移°?上¦?去¨£¤时º¡À

 

            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor;");//鼠º¨®标À¨º移°?开a时º¡À

 

        }

        if (e.Row.RowType == DataControlRowType.Footer)

 

        {

           ((Label)(e.Row.FindControl("lb_RecordNumber"))).Text = "共2有®D" + TotalRowsCount + "条¬?记?录?";

          (e.Row.FindControl("lb_PageCount") as Label).Text = "第̨²" + (gv_NewsContent.PageIndex + 1).ToString() + "页°3" + "共2" + (gv_NewsContent.PageCount.ToString()) + "页°3";

        }

 

    }

 

    protected void gv_NewsContent_RowEditing(object sender, GridViewEditEventArgs e)

    {

        gv_NewsContent.EditIndex = e.NewEditIndex;

        SetBind();

    }

    protected void gv_NewsContent_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

    {

        gv_NewsContent.EditIndex = -1;

        SetBind();

    }

    protected void gv_NewsContent_RowUpdating(object sender, GridViewUpdateEventArgs e)

    {

         Model.ContentInfo ci = new ContentInfo();

         BLL.Content ct = new BLL.Content();

         int iIndex=Convert.ToInt32(e.RowIndex);

        GridViewRow gvr=gv_NewsContent.Rows[iIndex];

        ci.ID=Convert.ToInt32(gv_NewsContent.DataKeys[iIndex].Value);

        ci.Title=(gvr.FindControl("tb_Title") as TextBox).Text.Trim();

        ci.Contents=(gvr.FindControl("tb_Contents") as TextBox).Text.Trim();

        ci.AddDate= Convert.ToDateTime((gvr.FindControl("tb_AddDate") as TextBox ).Text.Trim());

        ct.UpdateContentInfo(ci);

        gv_NewsContent.EditIndex = -1;

        SetBind();

 

 

    }

    protected void gv_NewsContent_RowDeleting(object sender, GridViewDeleteEventArgs e)

    {

       

        int iIndex =Convert.ToInt32 (e.RowIndex);

        ct.DeleteContentInfo(Convert.ToInt32(gv_NewsContent.DataKeys[iIndex].Value));

        SetBind();

       

    }

    protected void gv_NewsContent_PageIndexChanging(object sender, GridViewPageEventArgs e)

    {

        gv_NewsContent.PageIndex = e.NewPageIndex;

        SetBind();

    }

}

 

 

 

 

 

 

原文地址:https://www.cnblogs.com/liuyuanhao/p/3097415.html