Lớp DataAccess và cách thực hiện mô hình 3 lớp

Saturday, May 30, 2015
Các bài trước tại blog Đôn Bá Đạo là quá đủ cho công việc lập trình mô hình 3 lớp sử dụng procdure.
#TeamThichDiHoc

Lớp dataAccess


using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace DataAccess
{
    public class Data
    {
        /// 
        /// Hàm tạo connect kết nối cơ sở dữ liệu
        /// 
        public SqlConnection conn;
        public SqlDataAdapter myAdapter;
        public Data()
        {
            conn = new SqlConnection("Initial Catalog=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=kiemtra185;Data Source=.");
        }
        public SqlConnection openConnect()
        {
            if (conn.State == ConnectionState.Closed || conn.State == ConnectionState.Broken)
            {
                conn.Open();
            }
            return conn;
        }
        /// 
        /// Hàm lấy giá trị bảng từ Procdure trong sql
        /// 
        /// Tên của procdure
        /// tham số của procdure
        /// trả về 1 datatable
        public DataTable executeSelectQuery(String _query, SqlParameter[] sqlParameter)
        {
            SqlCommand myCommand = new SqlCommand();
            DataTable dataTable = new DataTable();
            myAdapter = new SqlDataAdapter();
            conn = openConnect();
            dataTable = null;
            DataSet ds = new DataSet();
            try
            {
                myCommand.Connection = conn;
                myCommand.CommandText = _query;
                myCommand.Parameters.AddRange(sqlParameter);
                myCommand.ExecuteNonQuery();
                myAdapter.SelectCommand = myCommand;
                myAdapter.Fill(ds);
                dataTable = ds.Tables[0];
            }
            catch (SqlException e)
            {
                return null;
            }
            return dataTable;
        }
        /// 
        /// Hàm thêm mới , xóa ,sửa dữ liệu với procudre
        /// 
        /// Truyền tên của procdure trong SQL
        /// Khởi tạo 1 sqlparameter dạng mảng để truyền tham số về
        /// Trả về kiểu số nguyên
        public int executeInsertQuery(String _query, SqlParameter[] sqlParameter)
        {
            int kq = -1;
            SqlCommand myCommand = new SqlCommand();
            SqlConnection conn = openConnect();
            myAdapter=new SqlDataAdapter ();
            myCommand.Connection = conn;
            myCommand.CommandText = _query;
            myCommand.Parameters.AddRange(sqlParameter);
            myAdapter.InsertCommand = myCommand;
            //conn.Open();
            return kq = myCommand.ExecuteNonQuery();
    }
}

Đối với cơ sở dữ liệu có nhiều table thì chúng ta sẽ tạo ra nhiều lớp để thực hiện công việc insert,update ,show dữ liệu
Solution c#

Hãy để ý Dmlop đó chính là tên table trong CSDL và đó cũng sẽ là một class , một đối tượng để chúng ta làm việc.

Class DmLop trong C#



using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using DataAccess;
using System.Windows.Forms;

namespace BussinessLogic
{
    
    
    public class DmLop
    {
        private string malop;

        public string Malop
        {
            get { return malop; }
            set { malop = value; }
        }
        private string tenlop;

        public string Tenlop
        {
            get { return tenlop; }
            set { tenlop = value; }
        }


        Data da = new Data();
        public DataTable showTblClass()
        {
            SqlParameter[] sqlPara = new SqlParameter[0];           
            return da.executeSelectQuery("pc_showDMLOP",sqlPara);
        }
        public int InsertDmLop(DmLop Lop)
        {
            SqlParameter[] sqlPara = { new SqlParameter("@malop", SqlDbType.NVarChar, 50),
                                         new SqlParameter("@tenlop", SqlDbType.NVarChar, 50) };
            sqlPara[0].Value = Lop.malop;
            sqlPara[1].Value = Lop.tenlop;
            return da.executeInsertQuery("pc_InsertDmLOP @malop,@tenlop", sqlPara);           
        }

        public int DeleteDmLop(string malop, string tenlop)
        {
            SqlParameter[] sqlPara = new SqlParameter[2];
            sqlPara[0] = new SqlParameter("@malop", SqlDbType.NVarChar, 50);
            sqlPara[0].Value = malop;
            sqlPara[1] = new SqlParameter("@tenlop", SqlDbType.NVarChar, 50);
            sqlPara[1].Value = tenlop;
            return da.executeInsertQuery("pc_DeleteDmLop @malop,@tenlop", sqlPara);  
        }
        public int UpdateDmLop(string malop, string tenlop)
        {
            SqlParameter[] sqlPara = new SqlParameter[2];
            sqlPara[0] = new SqlParameter("@malop", SqlDbType.NVarChar, 50);
            sqlPara[0].Value = malop;
            sqlPara[1] = new SqlParameter("@tenlop", SqlDbType.NVarChar, 50);
            sqlPara[1].Value = tenlop;
            return da.executeInsertQuery("pc_updateDmLOP @malop,@tenlop", sqlPara);
        }
        public void rowsClick(string malop, string tenlop,DataGridView dgv,DataGridViewCellMouseEventArgs e)
        {
            
            DataGridViewRow dr = new DataGridViewRow();
            dr = dgv.Rows[e.RowIndex];
            malop = dr.Cells[0].Value.ToString();
            dr.Dispose();
        }
    }
    
}

Insert dữ liệu vào form chính



//Thêm dữ liệu.
try
            {
                if (txtMalop.Text != "" || txtTenlop.Text != "")
                {
                    DmLop dmLop = new DmLop();
                    dmLop.Malop = txtMalop.Text;
                    dmLop.Tenlop = txtTenlop.Text;
                 
                    if (dmLop.InsertDmLop(dmLop) > 0)
                    {
                        lblMessage.Text = "* Bạn đã thêm thành công";
                        dataShowDMLOP();                        
                    }
                    else
                    {
                        lblMessage.Text ="* Bạn đã thêm thất bại";
                    }                   
                }
            }
            catch(Exception ex)
            {
                lblMessage.Text = ex.Message;
            }

//Hiển thị dữ liệu
public void dataShowDMLOP()
        {
            DmLop dmLop = new DmLop();
            grid_showLop.DataSource= dmLop.showTblClass();
        }


Quy cách đặt tên

Đối với Class
Class+Tên Table
Ví dụ:
ClassDeskGroup
Đối với Form
Tdh+Tên table
Ví Dụ:
TdhDeskGroup

Đối với Hàm + Procdure
Procdure
sp_+Tên proc
Ví dụ
sp_InsertDesk

Tất cả đều đặt tên tiếng anh