ASP.NET实现三层架构网站创建流程

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011028345/article/details/71081126

1.新建项目—>Visual C#—>Web—>ASP.NET空Web应用程序  或者  新建网站—>ASP.NET空网站

2.在解决方案处右击—>新建项目—>Windows—>类库,分别创建三层架构,Model(实体层)、Dll(逻辑层)、DAL(数据层),在每一层中创建如下图。


3.创建好三层类库后,在Model类库项目上右击,选择添加—>类,并命名,如下图。


4.在创建好类之后(每一个类对应数据库中的一个表),输入private string Sname(string是数据库中字段类型,Sname是数据库中字段名,与自己的数据库表相对应),如何对private string Sname选中—>右击—>选择重构—>封装字段,然后点击确定即可,实现了对数据库中表的一个字段进行封装,其余字段封装步骤跟上述一样,在创建完之后点击工具栏处的“生成”—>生成Model即可。操作步骤如下图,我的封装后的代码如下(根据自己的数据库表进行封装)。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Model
{
    public class Users
    {
        private string Sname;//字段类型和字段名要与数据库对应

        public string Sname1//封装后的字段
        {
            get { return Sname; }
            set { Sname = value; }
        }

        private string Ssex;

        public string Ssex1
        {
            get { return Ssex; }
            set { Ssex = value; }
        }

        private string Snumber;

        public string Snumber1
        {
            get { return Snumber; }
            set { Snumber = value; }
        }

        private string Sgrade;

        public string Sgrade1
        {
            get { return Sgrade; }
            set { Sgrade = value; }
        }

        private string Steacher;

        public string Steacher1
        {
            get { return Steacher; }
            set { Steacher = value; }
        }

        private string Sid;

        public string Sid1
        {
            get { return Sid; }
            set { Sid = value; }
        }

    }
}


5.对DAL层进行代码的编写,主要分为:(1)数据库连接函数,(2)执行sql语句函数,(3)sql语句书写和相应参数存储函数,注意:要在文件头部引用using System.Data; using System.Data.SqlClient; using Model; 前两个是asp.net集成的数据库操作库,调用其中相关函数、变量即可,最后一个是我们自己创建的Model类(在使用using Model命令之前需要将Model这个类在DAL这个项目中引用,在DAL项目中的“引用”处右击,选择添加引用,选择项目找到Model这个项目类确定即可)。其中sql语句执行函数根据返回类型不同有多种,自己可查相关资料学习,sql语句中相应字段实参的存储、传递方法也多种,自己可查相关资料学习,我的DAL代码如下。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using Model;

namespace DAL
{
    public class UserService
    {

        //连接数据库
        public static SqlConnection connection;
        public static SqlConnection Connection
        {
            get
            {
                if (connection == null)
                {
                    //远程连接数据库命令(前提远程数据库服务器已经配置好允许远程连接)
                    string strConn = @"Data Source=172.18.72.158;Initial Catalog=WebKuangjia;User ID=sa;Password=LIwei123;Persist Security Info=True";

                    //连接本地数据库命令
                    //string strConn = @"Data Source=.;Initial Catalog=WebKuangjia;Integrated Security=True";

                    connection = new SqlConnection(strConn);
                    connection.Open();
                }
                else if (connection.State == ConnectionState.Closed)
                {
                    connection.Open();
                }
                else if (connection.State == ConnectionState.Broken)
                {
                    connection.Close();
                    connection.Open();
                }
                return connection;
            }
        }

        //执行sql语句,返回被修改行数
        public static int ExecuteCommand(string commandText, CommandType commandType, SqlParameter[] para)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = Connection;
            cmd.CommandText = commandText;
            try
            {
                if (para != null)
                {
                    cmd.Parameters.AddRange(para);
                }
                return cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                connection.Close();
                cmd.Dispose();
            }
        }

        //执行sql语句,返回数据库表
        public static DataTable GetDataTable(string commandText, CommandType commandType, SqlParameter[] para)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = Connection;
            cmd.CommandText = commandText;
            cmd.CommandType = commandType;
            try
            {
                if (para != null)
                {
                    cmd.Parameters.AddRange(para);
                }
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable temp = new DataTable();
                da.Fill(temp);
                return temp;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                connection.Close();
                cmd.Dispose();
            }
        }

        //增加用户
        public static bool AddStudent(Users user)
        {
            string sql = "insert into Student(Sname,Ssex,Snumber,Sgrade,Steacher)" + "values(@name,@sex,@number,@grade,@teacher)";//sql语句字符串
            if (user.Ssex1==null)
            {
                user.Ssex1 = "";
            }
            if (user.Sgrade1 == null)
            {
                user.Sgrade1= "";
            }
            if (user.Steacher1 == null)
            {
                user.Steacher1 = "";
            }
            SqlParameter[] para = new SqlParameter[]//存储相应参数的容器
            {
                new SqlParameter("@name",user.Sname1),
                new SqlParameter("@sex",user.Ssex1),
                new SqlParameter("@number",user.Snumber1),
                new SqlParameter("@grade",user.Sgrade1),
                new SqlParameter("@teacher",user.Steacher1),
            };
            int count = ExecuteCommand(sql, CommandType.Text, para);//调用执行sql语句函数
            if (count>0)
            {
                return true;
            }
            else
            {
                return false;
            }

        }

        //查询数据库表
        public static DataTable Selecttable()
        {
            string sql = "select * from Student";
            return GetDataTable(sql, CommandType.Text, null);
        }

        //删除用户
        /****************删除用户返回影响行数*****************/
        public static bool DeleteStudentBySnumber(string number)
        {
            string sql = "delete from Student where Snumber=@number";
            SqlParameter[] para = new SqlParameter[]
            {
                new SqlParameter("@number",number),
            };
            int count = ExecuteCommand(sql, CommandType.Text, para);
            if (count>0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /****************删除用户返回表*****************/
        public static DataTable DeleteStudentBySid(int id)
        {
            string sql = "delete from Student where Sid=@id";
            SqlParameter[] para = new SqlParameter[]
            {
                new SqlParameter("@id",id),
            };
            return GetDataTable(sql, CommandType.Text, para);
        }

        //修改用户
        public static bool ModifyStudent(Users user)
        {
            string sql = "update Student set Sname=@name,Ssex=@sex,Snumber=@number,Sgrade=@grade,Steacher=@teacher where Sid=@id";
            SqlParameter[] para = new SqlParameter[]
             {
                new SqlParameter("@name",user.Sname1),
                new SqlParameter("@sex",user.Ssex1),
                new SqlParameter("@number",user.Snumber1),
                new SqlParameter("@grade",user.Sgrade1),
                new SqlParameter("@teacher",user.Steacher1),
                new SqlParameter("@id",user.Sid1),
             };
            int count = ExecuteCommand(sql, CommandType.Text, para);
            if (count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        //查询用户
        public static bool QueryStudent(string number)
        {
            string sql = "select * from Student where Snumber=@number";
            SqlParameter[] para = new SqlParameter[]
            {
                new SqlParameter("@number",number),
            };
            int count = ExecuteCommand(sql, CommandType.Text, para);
            if (count>0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
6.Dll层(逻辑层),只是一个中间层,负责参数的传递和调用DAL中的函数,注意头文件需要包含:using System.Data;using System.Data.SqlClient;using Model;using DAL;
将Model和DAL类进行包含(先引用这两个类,引用方法在步骤五中已经介绍),Dll层每个函数的返回类型需要与DAL中相应函数的返回类型一致,我的Dll代码如下。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using Model;
using DAL;

namespace Dll
{
    public class UserManage
    {
        public static bool add(Users user)
        {
            return UserService.AddStudent(user);
        }
        public static bool delete(string number)
        {
            return UserService.DeleteStudentBySnumber(number);
        }
        public static bool xiugai(string number)
        {
            return UserService.QueryStudent(number);
        }
        public static bool modify(Users user)
        {
            return UserService.ModifyStudent(user);
        }
        public static bool select(string number)
        {
            return UserService.QueryStudent(number);
        }
        public static DataTable table()
        {
            return UserService.Selecttable();
        }
        public static DataTable deletebyid(int id)
        {
            return UserService.DeleteStudentBySid(id);
        }
    }
}

7.在三层架构文件创建成功之后,只需要在前台引用Model和Dll即可,在using中添加using System.Data;using System.Data.SqlClient;using Model;using Dll;,剩余的就是控件的使用了,我用的是gridview控件进行数据表的操作,关于gridview控件的详细使用参考http://blog.csdn.net/21aspnet/article/details/1540301。我的前台代码如下。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Model;
using Dll;

namespace WebKuangJia
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           if (!IsPostBack)//初次加载该页
            {
                gvbind();
           }

        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string number = GridView1.Rows[e.RowIndex].Cells[3].Text;
            UserManage.delete(number);
           // GridView1.DataBind();
            gvbind();
        }

        protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            GridView1.SelectedIndex = e.NewSelectedIndex;
            //GridView1.DataBind();
            gvbind();
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
           GridView1.EditIndex = e.NewEditIndex;
           // GridView1.DataBind();
           gvbind();
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            Users us = new Users();
            us.Sid1 = GridView1.DataKeys[e.RowIndex].Value.ToString();//获取编辑行的数据主键值//((TextBox)GridView1.Rows[e.RowIndex].Cells[0].Controls[0]).Text;//[0].Controls[0]).Text;
            us.Sname1 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text.ToString().Trim();//获取编辑行的第1列的textbox控件中的内容赋值给Users对象us的Sname1封装字段
            us.Ssex1 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text.ToString().Trim();
            us.Snumber1 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text.ToString().Trim();
            us.Sgrade1 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text.ToString().Trim();
            us.Steacher1 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text.ToString().Trim();
            if (UserManage.modify(us))
            {
               GridView1.EditIndex = -1;
               //GridView1.DataBind();
               gvbind();
            }
            else
            {
                Response.Write("<script>alert('修改失败!')</script>");
            }

        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
           // GridView1.DataBind();
            gvbind();
        }

        private void gvbind()
        {
            DataTable list;//声明表变量
            list = UserManage.table();
            GridView1.DataSource = list;
            GridView1.DataKeyNames = new string[] { "Sid" };//主键
            GridView1.DataBind();
        }
    }
}
8.按照上述步骤即实现了网站的创建和数据的增删改查操作,其余网站的功能和上述类型,只需要添加相应的Model子类、Dll子类和DAL子类即可(所说的子类是在类库项目中添加的类而已,并进行相应代码的书写),我的数据库表如下,前台测试如下。





阅读更多
换一批

没有更多推荐了,返回首页