【问题标题】:Data Access Layer (DAL) design数据访问层 (DAL) 设计
【发布时间】:2010-10-11 09:18:03
【问题描述】:

我正在为我的数据访问层设计使用 .Net 企业库数据访问应用程序块。

在我的类别 DAL 类中,我有如下方法:

GetProductsInCategory(int CatId)、GetAllProducts、GetCategories 等

我的问题是:我把这行代码放在哪里?

DatabaseFactory.CreateDatabase("MyDB");

我应该把它放在上面的每个方法中,还是应该有一个基类,它将数据库对象返回到我的 DAL 类。

另外,我应该将这些 DAL 类方法保持为静态吗?

【问题讨论】:

    标签: c# data-access-layer


    【解决方案1】:

    我更喜欢返回常见对象(如连接)的基类,例如数据库。

    这里是设计数据访问层的参考:.NET Application Architecture: the Data Access Layer

    我使用 Microsoft Enterprise Library 数据访问应用程序块。它完成了这里提到的大部分事情。但是像连接或事务这样的常见东西会放在我的基类中。

    DataServiceBase 类提供 常见的数据访问功能,例如 打开数据库连接, 管理事务,设置 存储过程参数,执行 命令等等。其他 换句话说,DataServiceBase 类 包含通用数据库代码和 为您提供一套帮手 用于个人数据的方法 服务类。派生数据 服务类使用辅助方法 在 DataServiceBase 中用于特定的 目的,例如执行特定的 命令或运行特定查询。

    【讨论】:

    • 如果你有一个基类,那么你不需要工厂方法,因为派生类可以访问protected Database _myDatabase
    • @Ian Quigley :是的,您需要实例化您的“受保护数据库 _myDatabase”,因此您需要在基类的构造函数中使用工厂类。
    • 感谢您的提示..我将拥有从基类 DBManager 派生的所有 DAL 类。此类将有一个名为 GetDatabase() 的受保护方法,该方法将具有代码:return DatabaseFactory.CreateDatabase("我的数据库");我在派生类中的方法看起来像:...(在下一条评论中继续)
    • 公共数据集 GetProductsInCategory(int Category) {Database db = base.GetDatabase(); DbCommand dbCommand = db.GetStoredProcComman("GetProductsByCategory"); db.AddInParameter(dbCommand, "CategoryID", DbType.Int32, Category); return db.ExecuteDataSet(dbCommand);} 这个 DAL 设计看起来好吗?
    【解决方案2】:

    感谢您的提示..我将拥有从基类 DBManager 派生的所有 DAL 类。此类将有一个名为 GetDatabase() 的受保护方法,该方法将具有代码:return DatabaseFactory.CreateDatabase("MyDB");我在派生类中的方法看起来像:..

    public DataSet GetProductsInCategory(int Category) 
    {
    Database db = base.GetDatabase(); 
    DbCommand dbCommand = db.GetStoredProcComman("GetProductsByCategory"); 
    db.AddInParameter(dbCommand, "CategoryID", DbType.Int32, Category); 
    return db.ExecuteDataSet(dbCommand);
    } 
    

    这个 DAL 设计看起来好吗?

    【讨论】:

      【解决方案3】:

      我建议考虑使用 SubSonic 进行 DAL 和对象生成。它实现了 Microsoft 的应用程序块,但为您提供了简单(且强大)的查询功能,例如:

      SubSonic.Query qry = new SubSonic.Query(Usr.Schema);
      qry.SetSelectList(Usr.Columns.UserPkid);
      qry.QueryType = SubSonic.QueryType.Select;
      qry.AddWhere(Usr.UsernameColumn.ColumnName, SubSonic.Comparison.Equals, Username);
      
      using (IDataReader reader = qry.ExecuteReader())
      {
          while (reader.Read())
          {
              Trace.WriteLine("Fetched User Pkid [" + reader[Usr.Columns.UserPkid].ToString() + "]");
          }
      }
      

      当然,它实现了ActiveRecord 模式,因此对象类具有 .Delete()、.Add()、.Get() 类型的方法。

      【讨论】:

        猜你喜欢
        • 2011-11-02
        • 2012-08-18
        • 2010-12-03
        • 2012-06-06
        • 2013-12-05
        • 1970-01-01
        • 2010-12-24
        • 2010-11-06
        相关资源
        最近更新 更多