在c#, poco's和ado.net的存储库中,最好是一个类用于整个存储库还是每个实体几个类
本文关键字:存储 一个 用于 几个 实体 poco net ado | 更新日期: 2023-09-27 18:08:37
我正在为我的项目创建一个存储库,实际上是它的一个子集,使用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,它提出了另一种方法。这是一个相当简单的示例,我的存储库不需要那么复杂。
有不同的解决方案吗?在存储库的外部创建您的连接(或事务,或工作单元),并将其传递给存储库。像这样-
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
概念的内容,这可能适用于这里)
将类组织成可管理的组
在你的例子中,我认为Order和Customer应该属于OrderRepository。
产品将进入目录存储库。
如果类需要在单元测试时进行模拟,它们将进入自己的存储库。可以是PaymentRepository