【问题标题】:LINQ query methods in the data access layer(DAL)数据访问层 (DAL) 中的 LINQ 查询方法
【发布时间】:2011-05-04 07:17:41
【问题描述】:

一个基于经典 3 层的项目:UI(在这个问题中不重要)、业务逻辑层和数据访问层。我有几张桌子:CustomersProductsOrdersUsers。设计应该是:

//DAL methods
public IEnumerable<Customer> GetAllCustomers()
public IEnumerable<Product> GetAllProducts()
public IEnumerable<Order> GetAllOrders()
public IEnumerable<User> GetAllUsers()
//BLL methods
public IEnumerable<Order> GetOrders(long CustomerID)
public IEnumerable<Product> GetProducts(long CustomerID)
public IEnumerable<Product> GetProducts(long OrderID)

让我困惑的是,我发现 DAL 中的所有方法都是 GetAllXXXX。我不得不承认这个设计运行良好。在 DAL 中,只有 GetAll 方法。在 BLL 中,除了 GetAll 方法的组合操作(过滤/加入/选择)外,什么都没有。很奇怪吗?正确的方法是什么?

【问题讨论】:

    标签: c# .net linq architecture data-access-layer


    【解决方案1】:

    考虑您的数据访问层可能提供以下服务:

    • 创建
    • 更新
    • 删除
    • GetSingleCustomer()
    • CalculateUpperManagementTuesdayReport()

    我不会说这很奇怪,但也许您的 DAL 不需要提供这些服务,因为您的应用程序不需要它们。

    在 BL 中有您的过滤器/加入/选择,我更喜欢 IQueryable&lt;t&gt; 而不是 IEnumerable&lt;T&gt;。这意味着在 BL 代码中调用 Single()、First()、ToList()、Count() 等之前,不会执行 BL 代码中的给定语句。

    【讨论】:

      【解决方案2】:

      我的问题是,如果合并当前的 BLL 和 DAL,你会失去什么? - 他们似乎都在处理从持久数据(DB)到对象的桥梁。似乎是最简单的事情。 另一种看待它的方式是更改本地化?例如如果 DAL 层发生变化,那会是孤立的还是会波及上层(这是不可取的)。

      理想情况下,BLL 应该封装您的领域(即领域知识)的规则/工作流程。例如如果某些客户受到不同的对待。 DAL 的存在是将您的数据从持久状态转换为对象(或更高层使用的数据结构),反之亦然。这是我今天的理解......

      【讨论】:

        【解决方案3】:

        不,这并不奇怪,实际上这与我的做法非常相似。

        对我来说只有区别:

        • 我使用IQueryable&lt;T&gt; 而不是IEnumerable&lt;T&gt;(以获得延迟执行)
        • 我有一个通用存储库 (Repository&lt;T&gt;):
          • IQueryable&lt;T&gt; Find()
          • void Add(T)
          • 等等等等

        这样,我的存储库保持干净/简单。

        所以你的 BLL 可以这样实现:

        public IEnumerable<Order> GetOrders(long CustomerID)
        {
           Repository<Order> orderRepository = new Repository<Order>(); // should use DI here, but i digress
           return orderRepository
                     .Find() // no query executed...
                     .Where(o => o.CustomerID == CustomerID) // still nothing...
                     .ToList(); // query executed, with BL applied! cool!
        }
        

        让 BLL 进行投影/工作/逻辑。存储库只处理 T 的持久性,不关心实际类型或任何业务逻辑。

        反正我就是这么干的。

        【讨论】:

          猜你喜欢
          • 2010-10-11
          • 2012-08-18
          • 2013-12-05
          • 2011-11-02
          • 2012-01-05
          • 2016-02-23
          • 1970-01-01
          • 2014-08-05
          • 2011-08-02
          相关资源
          最近更新 更多