【问题标题】:In a repository with c#, poco's and ado.net what is best, one class for entire repository or several classes per entity?在具有 c#、poco 和 ado.net 的存储库中,最好的是一个类用于整个存储库还是每个实体有几个类?
【发布时间】:2013-04-02 21:51:57
【问题描述】:

我正在为我的项目创建一个存储库,实际上是它的一个子集,包含 c#、poco 和旧的 ado.net(没有 ORM)。 我有几个实体,我的存储库将通过 DAL 对它们进行 CRUD。 我的 DAL 是 IDisposable,因此我在实例化它时设法打开了与数据库的连接,并在 Dispose 方法中关闭了该连接。 现在我想知道,我应该在存储库中为每个实体使用一个类还是为所有实体使用一个巨大的类? 第二种方法将允许我打开连接,根据需要检索许多实体,然后关闭它。第一个我必须为每个实体打开和关闭一个连接,如下所示:

 //One big class for all entities, opens one connection
 using(RepositoryForAll rfa = new RepositoryForAll())
 {
     Customer c = rfa.GetCustomer(Customerid);
     Order o = rfa.GetOrder(OrderId);
 }
 //closes the connection

 //One repository class per entity, also one connection
 using(RepositoryCustomer customers = new RepositoryCustomer())
 {
     var c = customers.Get(CustomerId);
 }
 //closes the connection for RepositoryCustomer

 using(RepositoryOrder orders = new RepositoryOrder())
 {
     var c = orders.Get(OrderId);
 }
 //closes the connection for RepositoryOrder 

这有意义吗? 我在某本书中读到了 AggregateRoot,它提出了另一种方法。 这是一个相当简单的示例,我的存储库不必那么复杂。

【问题讨论】:

    标签: c# ado.net repository-pattern poco


    【解决方案1】:

    不同的解决方案怎么样?在存储库外部创建您的连接(或事务或工作单元),并将其传递给存储库。
    就这样——

    using(var tx = new Transaction())
     {
         RepositoryCustomer customers = new RepositoryCustomer(tx)
         RepositoryOrder orders = new RepositoryOrder(tx)
         var c = customers.Get(CustomerId);
         var o = orders.Get(OrderId);
     }  
    

    (当然,这只是一个简单的示例;我建议使用某种 IoC 机制而不是自己实例化对象。
    此外,您可能想阅读一些关于 Unit of work 概念的信息,这可能适用于此处)

    【讨论】:

      【解决方案2】:

      在可管理的组中组织课程。

      在您的情况下,我认为 Order 和 Customer 应该属于 OrderRepository。

      产品将进入 CatalogueRepository。

      如果在单元测试时需要模拟类,它们会进入自己的存储库。那可能是 PaymentRepository。

      【讨论】:

      • 这是我上面提到的聚合根,并没有解决我的问题...还是谢谢!
      猜你喜欢
      • 2012-03-10
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      • 2019-01-17
      • 1970-01-01
      • 2012-06-20
      • 1970-01-01
      • 2020-03-12
      相关资源
      最近更新 更多