.net中实现简单三层架构

     这篇文章讨论如何在.net中实现3层架构,使用MS sqlserver2005数据库存储数据。在此,我在3层架构中实现一个小型的可复用的组件保存客户数据。并提供添加,更新,查找客户数据的功能。


     什么是3层架构?

    3层架构是一种“客户端-服务器”架构,在此架构中用户接口,商业逻辑,数据保存以及数据访问被设计为独立的模块。主要有3个层面,第一层(表现层,GUI层),第二层(商业对象,商业逻辑层),第三层(数据访问层)。这些层可以单独开发,单独测试。

    为什么要把程序代码分为3层。把用户接口层,商业逻辑层,数据访问层分离有许多的优点。

    在快速开发中重用商业逻辑组件,我们已经在系统中实现添加,更新,删除,查找客户数据的组件。这个组件已经开发并且测试通过,我们可以在其他要保存客户数据的项目中使用这个组件。

    系统比较容易迁移,商业逻辑层与数据访问层是分离的,修改数据访问层不会影响到商业逻辑层。系统如果从用SQL Server存储数据迁移到用Oracle存储数据,并不需要修改商业逻辑层组件和GUI组件

    系统容易修改,假如在商业层有一个小小的修改,我们不需要在用户的机器上重装整个系统。我们只需要更新商业逻辑组件就可以了。

    应用程序开发人员可以并行,独立的开发单独的层。

    代码

    这个组件有3层,第一个层或者称为GUI层用aspx页面实现,叫做defalt.aspx。第二层或者称为商业逻辑层,叫做BOEmployee,是Bussniess Object Employee的缩写。最后是第三层或者称为数据层,叫做DAEmployee,是Data Access Employee的缩写。

  用户接口层(表示层default.cs代码)

 下面是用户接口成的一段代码,我只选取了调用商业逻辑层的一部分代码。

 public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        { }

    }
    protected void ButtonAdd_Click(object sender, EventArgs e)
    {
        BOEmployee employee = new BOEmployee();
        employee.EmployeeId = TextBoxEmployeeID.Text;
        employee.FirstName = TextBoxFirstName.Text;
        employee.LastName = TextBoxLastName.Text;
        employee.HomePhone = TextBoxHomePhone.Text;
        employee.Address = TextBoxAddress.Text;
        employee.Add();
    }
    protected void ButtonFind_Click(object sender, EventArgs e)
    {
        BOEmployee employee = new BOEmployee();
        string str = TextBoxFind.Text;
      
        DataSet ds = new DataSet();
        ds=employee.Find(str);
       
        foreach( DataRow row in ds.Tables[0].Rows)
        {
            TextBoxEmployeeID.Text = row["EmployeeID"].ToString();
            TextBoxFirstName.Text = row["FirstName"].ToString();
            TextBoxLastName.Text = row["LastName"].ToString();
            TextBoxAddress.Text = row["Address"].ToString();
            TextBoxHomePhone.Text=row["HomePhone"].ToString();
        }
       
    }
    protected void ButtonUpdate_Click(object sender, EventArgs e)
    {
        BOEmployee employee = new BOEmployee();
        employee.EmployeeId = TextBoxFind.Text;
        employee.FirstName = TextBoxFirstName.Text;
        employee.LastName = TextBoxLastName.Text;
        employee.HomePhone = TextBoxHomePhone.Text;
        employee.Address = TextBoxAddress.Text;
        employee.Update();
    }
}

  商业逻辑层

  下面是商业逻辑层的所有代码,主要包括定义Employee对象的属性。但这仅仅是个虚构的Employee对象,如果需要可以加入其他的属性。商业逻辑层还包括添加,更新,查找,等方法。

    商业逻辑层是一个中间层,处于GUI层和数据访问层中间。他有一个指向数据访问层的引用 employee = new DAEmployee().而且还引用了System.Data名字空间。商业逻辑层使用DataSet返回数据给GUI层

以下是实现商业逻辑层的代码:

/// <summary>
/// BOEmployee 的摘要说明
/// </summary>
namespace _3tierarchitecture
{
    public class BOEmployee
    {
        public BOEmployee()
        {
            //
            // TODO: 在此处添加构造函数逻辑

            //An instance of the Data access layer!
            employee = new DAEmployee();
        }
        //Employee property
        private string firstName;
        private string lastName;
        private string homePhone;
        private string address;
        private DAEmployee employee;
 
       
        //Employee Field
        public string Address
        {
            get { return this.address; }
            set
            {
              this.address = value;
              if (this.address == "")
                  throw new Exception("please provide address");

            }
        }
   

        public string HomePhone
        {
            get { return this.homePhone; }
            set
            {
                this.homePhone = value;
                if (this.homePhone == "")
                    throw new Exception("please provide homePhone");
                          
            }
        }
        private string employeeId;

        public string EmployeeId
        {
            get { return this.employeeId; }
            set
            {
                this.employeeId = value;
                if (this.employeeId == "")
                    throw new Exception("please provide employeeid");
            }
        }
    
        public string FirstName
        {
            get
            {
                return this.firstName;
            }
            set
            {

                    this.firstName = value;
                    if (this.firstName == "")
                        throw new Exception("please provide firstname");


            }

        }

        public string LastName
        {
            get { return this.lastName; }
            set
            { 
               this.lastName = value;
               if (this.lastName == "")
                 throw new Exception("please provide lastname");
           
            }
        }

         


        /// <SUMMARY>

        /// Function Add new employee. Calls

        /// the function in Data layer.

        /// </SUMMARY>
        public void Add()
        {
            employee.Add(this);
 
        }
        ///<SUMMARY>
        ///Function Update  new employee calls
        ///the function in data layer
        ///</SUMMARY>
        public void Update()
        {
            employee.Update(this);

        }
        ///<SUMMARY>
        /// function in Data layer.

        /// It returns the details of the customer using

        /// customer ID via a Dataset to GUI tier.
        /// </SUMMARY>
        public DataSet Find(string str)
        {
            if (str == "")
                throw new Exception("Please provide Employeeid");
            DataSet ds = new DataSet();
            ds=employee.Find(str);
            return ds;


        }

 

    }
}
 数据访问层

 

    数据层包括处理MS sqlserver 2005数据库的细节。所有这些细节都是透明的,不会影响到商业逻辑层。数据访问层有个指向商业逻辑层的引用BOEmployee employee。为了应用方便并且支持其他数据库。

/// <summary>
/// DACustomer 的摘要说明
/// </summary>
namespace _3tierarchitecture
{
    public class DAEmployee
    {
        //数据库连接
       private  SqlConnection myConnection=new SqlConnection(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString);
        public DAEmployee()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
        private string strTable = "";
        private string strFields = "";
        private string strValues = "";
        private string strInsert = "";

        private const string thisTabel = "Employees";
        private const string employeeId = "EmployeeID";
        private const string lastName = "LastName";
        private const string firstName = "FirstName";
        private const string address = "Address";
        private const string homePhone = "HomePhone";

        //增记录语句
        private string BuildAddString(BOEmployee employee)
        {
            // these are the constants as
            // set in the top of this module.
            strTable = "Insert into " + thisTabel;

            strFields = " (" + employeeId +

            "," + firstName+

            "," + lastName +

            "," + address +

            "," + homePhone + ")";

            //these are the attributes of the

            //customer business object.

            strValues = " Values ( '" + employee.EmployeeId +

            "' , '" + employee.FirstName +

            "' , '" + employee.LastName +

            "' , '" + employee.Address +

            "' , '" + employee.HomePhone + "' )";

            strInsert = strTable + strFields + strValues;

            return strInsert;

        }
        /// <summary>
        /// 增加一个数据记录
        /// </summary>
        /// <param name="employee"></param>
        public void Add(BOEmployee employee)
        {
            string str = BuildAddString(employee);
   
        
            SqlCommand myCommand = new SqlCommand(str,myConnection);
            ConOpen();
            myCommand.ExecuteNonQuery();
      
            ConClose();

          
           
        }
        ///<summary>
        ///更新一个记录
       ///</summary>
        public void Update(BOEmployee employee)
        {
            //打开数据库
           
            string updateString = "update " + thisTabel + " set " + firstName + "='" + employee.FirstName + "'," + lastName + "='" + employee.LastName + "'," + address + "='" + employee.Address + "'," + homePhone + "='" + employee.HomePhone + "' where " +
                employeeId + "='" + employee.EmployeeId+"'";
            SqlCommand myCommand = new SqlCommand(updateString,myConnection);
            ConOpen();
            myCommand.ExecuteNonQuery();

            //关闭数据库
            ConClose();
 
        }

        ///<summary>
        /// 查找一个记录
        ///</summary>
        public DataSet Find(string argStr)
        {
            DataSet ds = null;

            string selectStr = "select * from " + thisTabel + " where employeeId= '" + argStr + "'";


            //SqlCommand myCommand = new SqlCommand(selectStr,myConnection);
            ds = new DataSet();
            //打开数据库
            ConOpen();
            SqlDataAdapter da = new SqlDataAdapter(selectStr,myConnection);
            da.Fill(ds,thisTabel);

         
            //关闭数据库
            ConClose();
            return ds;

 
        }

 

 


        //打开数据库连接
        public void ConOpen()
        {
            myConnection.Open();
        }
        //关闭数据库连接
        public void ConClose()
        {
          myConnection.Close();
        }

 

    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值