6

我是 3 层架构的新手,下面是我的 DAL 代码

public static int Insert(string firstname, string lastname, DateTime dob, string gender,string email, string password)
    {
        // bool flag = false;
        SqlParameter pid;
        SqlParameter result;

        SqlConnection con = Generic.DBConnection.OpenConnection();

        try
        {

            SqlCommand cmd1 = new SqlCommand("Insertreg", con);
            cmd1.CommandType = CommandType.StoredProcedure;
            cmd1.Parameters.AddWithValue("@FirstName", firstname);
            cmd1.Parameters.AddWithValue("@LastName", lastname);
            cmd1.Parameters.AddWithValue("@Dob", dob);
            cmd1.Parameters.AddWithValue("@Gender", gender);
           cmd1.Parameters.AddWithValue("@EmailId", email);
            cmd1.Parameters.AddWithValue("@Password", password);
            result = cmd1.Parameters.Add("@result", System.Data.SqlDbType.Int);
            result.Direction = System.Data.ParameterDirection.Output;
            pid = cmd1.Parameters.Add("@id", System.Data.SqlDbType.Int);
            pid.Direction = System.Data.ParameterDirection.Output;
            return cmd1.ExecuteNonQuery();


            con.Close();

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

这在 BAL

 public int insert(string firstname,string lastname,DateTime dob,string gender,string email,string password)
    {
      ProfileMasterDAL dal=new ProfileMasterDAL();
      try
      {
          return ProfileMasterDAL.Insert(firstname, lastname, dob, gender,email, password);
      }
      catch (Exception ex)
      {

          throw ex;
      }
        finally
      {
          dal = null;
      }

    }

我的用户界面

  ProfileMasterBLL pmBLL = new ProfileMasterBLL();
 pmBLL.insert(firstname, lastname, dob, gender, mobile, country, state, email, password);

这是在 3 层编码的正确方法吗?我的意思是如何调用从 DAL 到 BAL 和 UI 的方法?如果不建议我一些好方法。谢谢。

4

4 回答 4

6

通常我会执行以下操作:

  1. 定义一个业务层(BL,你称之为 BAL)。这包含您的业务实体的定义。它还为您使用的任何模式(存储库、上下文等)定义了检索/保存/删除数据的接口。
  2. 定义数据访问层 (DAL)。这包含检索/保存/删除接口的实际实现。
  3. 定义一个 UI 层。这包含可以使用 BL 加载数据的 UI 元素(表单、控件、模型、控制器等)。

参考文献如下:

  1. BL 不知道 DAL 或 UI。
  2. DAL 知道 BL。DAL 不知道 UI。
  3. UI 知道 BL。UI 不知道 DAL。

对您来说最大的问题可能是,当 BL 不知道 DAL 时,它如何检索/保存/删除数据,因此无法在 DAL 中创建类的实例。好吧,这就是依赖注入派上用场的地方。您所要做的就是将 DAL 类注入 BL 接口。

希望这是有道理的。我将它用作我的标准 3 层实现,它绝对没有问题。具体来说,我将Entity Framework 与 POCO 一起用于实体,我使用的 DI 是自定义的,但任何一个都可以。

更新

BL 不知道 DAL。

  • BL 定义了一个接口(我们称之为 IRepository),它可以用来做它需要做的事情。
  • DAL 定义了一个实现接口 IRepository 的类(Repository)。所以存储库的实际实现是在 DAL 中。
  • 显然 BL 不能直接创建存储库的实例。这就是依赖注入的用武之地,这允许开发人员创建一个通常无法完成的类的实例。一个简单粗暴的版本是使用反射

我希望这更有意义。

于 2012-08-31T12:03:45.723 回答
0

它可能会帮助您查看一些实际代码。我建议您下载NetTiers,针对您的数据库模式运行它,并查看输出代码以了解实现细节。

于 2012-08-31T15:12:21.880 回答
0

您可以为 3 层架构提供以下示例代码:-

类-BAL.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;

public class BAL
{
    DAL objDAL;
    public BAL()
    {

    }

    public string _Name;
    public string Name
    {
        get { return _Name; }
        set { _Name = value; }
    }

    public int insert()
    {
        objDAL = new DAL();
        int val = 0;
        try
        {
            Hashtable objHash = new Hashtable();
            objHash.Add("@Name", Convert.ToString(_Name));
            val = objDAL.Insert("Your SP Name", objHash);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            objDAL = null;
        }
        return val;
    }
}

类 - DAL.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Collections;

public class DAL : IDisposable
{
    SqlConnection con;

    public DAL()
    {
        con = new SqlConnection("Connection String");
    }

    public int Insert(string CMD, Hashtable objHash)
    {
        int val = 0;
        try
        {
            SqlCommand cmd1 = new SqlCommand(CMD, con);
            cmd1.CommandType = CommandType.StoredProcedure;
            foreach (DictionaryEntry de in objHash)
            {
                cmd1.Parameters.AddWithValue(Convert.ToString(de.Key), Convert.ToString(de.Value));
            }
            con.Open();
            val = cmd1.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
        }
        return val;
    }

    #region IDisposable Members

    public void Dispose()
    {
        throw new NotImplementedException();
    }

    #endregion
}

用户界面:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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

    BAL objBAL;

    protected void Page_Load(object sender, EventArgs e)
    {
        Insert();
    }

    public void Insert()
    {
        int val = 0;
        objBAL = new BAL();
        objBAL.Name = "stackoverflow";
        try
        {
            val = objBAL.insert();
        }
        catch { }
        finally
        {
            objBAL = null;
        }
        if (val != 0)
        {
            //Insert sucessful
        }
        else
        {
            //Error in Insert.
        }
    }
}
于 2012-08-31T12:19:37.853 回答
0
using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Odbc;
using System.IO;
using System.ComponentModel;

namespace dal
{

    /// <summary>
    /// Summary description for Data Access Layer
    /// </summary>
    public class DataAccess
    {
        public string strConnectionString;
        private DbConnection objConnection;
        private DbCommand objCommand;
        private DbProviderFactory objFactory = null;
        private bool boolHandleErrors=false;
        private string strLastError;
        private bool boolLogError=false;
        private string strLogFile;

        public DataAccess()
        {

            //strConnectionString = ;
            strConnectionString = objCommon.GetConnectionString;
            objFactory = OleDbFactory.Instance;
            objConnection = objFactory.CreateConnection();
            objCommand = objFactory.CreateCommand();
            objConnection.ConnectionString = strConnectionString;
            objCommand.Connection = objConnection;
        }

        public bool HandleErrors
        {
            get
            {
                return boolHandleErrors;
            }
            set
            {
                boolHandleErrors = value;
            }
        }

        public string LastError
        {
            get
            {
                return strLastError;
            }
        }

        public bool LogErrors
        {
            get
-            {
                return boolLogError;
            }
            set
            {
                boolLogError = value;
            }
        }

        public string LogFile
        {
            get
            {
                return strLogFile;
            }
            set
            {
                strLogFile = value;
            }
        }

        public int AddParameter(string name, object value)
        {
            DbParameter p = objFactory.CreateParameter();
            p.ParameterName = name;
            p.Value = value;
            return objCommand.Parameters.Add(p);
        }

        public int AddParameter(string name, object value, ParameterDirection direction)
        {
            DbParameter p = objFactory.CreateParameter();
            p.ParameterName = name;
            p.Value = value;
            p.Direction = direction;
            return objCommand.Parameters.Add(p);
        }

        public int AddParameter(string name, object value, DbType type)
        {
            DbParameter p = objFactory.CreateParameter();
            p.ParameterName = name;
            p.Value = value;
            p.DbType = type;
            return objCommand.Parameters.Add(p);
        }

        public int AddParameter(DbParameter parameter)
        {
            return objCommand.Parameters.Add(parameter);
        }

        public DbCommand Command
        {
            get
            {
                return objCommand;
            }
        }

        public void BeginTransaction()
        {
            try
            {
                if (objConnection.State == System.Data.ConnectionState.Closed)
                {
                    objConnection.Open();
                }
                objCommand.Transaction = objConnection.BeginTransaction();
            }
            catch (Exception Ex)
            {
                HandleExceptions(Ex);
            }
        }

        public void CommitTransaction()
        {
            objCommand.Transaction.Commit();
            objConnection.Close();
        }

        public void RollbackTransaction()
        {
            objCommand.Transaction.Rollback();
            objConnection.Close();
        }

        public int ExecuteNonQuery(string query)
        {
            return ExecuteNonQuery(query, CommandType.Text, ConnectionState.CloseOnExit);
        }

        public int ExecuteNonQuery(string query, CommandType commandtype)
        {
            return ExecuteNonQuery(query, commandtype, ConnectionState.CloseOnExit);
        }

        public int ExecuteNonQuery(string query, ConnectionState connectionstate)
        {
            return ExecuteNonQuery(query, CommandType.Text, connectionstate);
        }

        public int ExecuteNonQuery(string query, CommandType commandtype, ConnectionState connectionstate)
        {
            objCommand.CommandText = query;
            objCommand.CommandType = commandtype;
            int i = -1;
            try
            {
                if (objConnection.State == System.Data.ConnectionState.Closed)
                {
                    objConnection.Open();
                }
                i = objCommand.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                HandleExceptions(ex);
            }
            finally
            {
                objCommand.Parameters.Clear();
                if (connectionstate == ConnectionState.CloseOnExit)
                {
                    objConnection.Close();
                }
            }

            return i;
        }

        public object ExecuteScalar(string query)
        {
            return ExecuteScalar(query, CommandType.Text, ConnectionState.CloseOnExit);
        }

        public object ExecuteScalar(string query, CommandType commandtype)
        {
            return ExecuteScalar(query, commandtype, ConnectionState.CloseOnExit);
        }

        public object ExecuteScalar(string query, ConnectionState connectionstate)
        {
            return ExecuteScalar(query, CommandType.Text, connectionstate);
        }

        public object ExecuteScalar(string query, CommandType commandtype, ConnectionState connectionstate)
        {
            objCommand.CommandText = query;
            objCommand.CommandType = commandtype;
            object o = null;
            try
            {
                if (objConnection.State == System.Data.ConnectionState.Closed)
                {
                    objConnection.Open();
                }
                o = objCommand.ExecuteScalar();
            }
            catch (Exception ex)
            {
                HandleExceptions(ex);
            }
            finally
            {
                objCommand.Parameters.Clear();
                if (connectionstate == ConnectionState.CloseOnExit)
                {
                    objConnection.Close();
                }
            }

            return o;
        }

        public DbDataReader ExecuteReader(string query)
        {
            return ExecuteReader(query, CommandType.Text, ConnectionState.CloseOnExit);
        }

        public DbDataReader ExecuteReader(string query, CommandType commandtype)
        {
            return ExecuteReader(query, commandtype, ConnectionState.CloseOnExit);
        }

        public DbDataReader ExecuteReader(string query, ConnectionState connectionstate)
        {
            return ExecuteReader(query, CommandType.Text, connectionstate);
        }

        public DbDataReader ExecuteReader(string query, CommandType commandtype, ConnectionState connectionstate)
        {
            objCommand.CommandText = query;
            objCommand.CommandType = commandtype;
            DbDataReader reader = null;
            try
            {
                if (objConnection.State == System.Data.ConnectionState.Closed)
                {
                    objConnection.Open();
                }
                if (connectionstate == ConnectionState.CloseOnExit)
                {
                    reader = objCommand.ExecuteReader(CommandBehavior.CloseConnection);
                }
                else
                {
                    reader = objCommand.ExecuteReader();
                }

            }
            catch (Exception ex)
            {
                HandleExceptions(ex);
            }
            finally
            {
                objCommand.Parameters.Clear();
            }

            return reader;
        }

        public DataSet ExecuteDataSet(string query)
        {
            return ExecuteDataSet(query, CommandType.Text, ConnectionState.CloseOnExit);
        }

        public DataSet ExecuteDataSet(string query, CommandType commandtype)
        {
            return ExecuteDataSet(query, commandtype, ConnectionState.CloseOnExit);
        }

        public DataSet ExecuteDataSet(string query, ConnectionState connectionstate)
        {
            return ExecuteDataSet(query, CommandType.Text, connectionstate);
        }

        public DataSet ExecuteDataSet(string query, CommandType commandtype, ConnectionState connectionstate)
        {
            DbDataAdapter adapter = objFactory.CreateDataAdapter();
            objCommand.CommandText = query;
            objCommand.CommandType = commandtype;
            adapter.SelectCommand = objCommand;
            DataSet ds = new DataSet();

            try
            {
                adapter.Fill(ds);
            }
            catch (Exception ex)
            {
                HandleExceptions(ex);
            }
            finally
            {
                objCommand.Parameters.Clear();
                if (connectionstate == ConnectionState.CloseOnExit)
                {
                    if (objConnection.State == System.Data.ConnectionState.Open)
                    {
                        objConnection.Close();
                    }
                }
            }
            return ds;
        }

        private void HandleExceptions(Exception ex)
        {

            throw ex;

        }

        private void WriteToLog(string msg)
        {
            StreamWriter writer = File.AppendText(LogFile);
            writer.WriteLine(DateTime.Now.ToString() + " - " + msg);
            writer.Close();
        }

        public void Dispose()
        {
            objConnection.Close();
            objConnection.Dispose();
            objCommand.Dispose();
        }



        public enum Providers
        {
            SqlServer, OleDb, Oracle, ODBC, ConfigDefined
        }

        public enum ConnectionState
        {
            KeepOpen, CloseOnExit
        }

        public interface ILoadFromDataRow
        {
            bool LoadFromDataRow(DataRow row);
        }


    }

}
于 2017-06-04T10:15:30.707 回答