实现存储库模式的正确方法是什么?以及如何使用它?



我有一个名为Product的对象,我想从所有产品(存储在SQL Server中(列表中检索某个产品的"物料清单"。我是否应该先创建 Product 对象,然后通过一种方法从我的存储库中获取数据,如下所示:

var productId = "1";
Product product = new Product(productId);
DataTable billOfMaterial = product.GetBillOfMaterial();

或者从静态存储库中检索数据通道,如下所示:

var productId = "1";
DataTable billOfMaterial = product.GetBillOfMaterial(productId);

或者也许像这样?

var productId = "1";
DataTable BillOfMaterial = ProductRepository.GetBillOfMaterial(productId);

或者,当我创建产品时,我会自动在产品的构造函数中获取账单:

var productId = "1";
Product product = new Product(productId);
DataGrid.DataSource = product.BillOfMaterial;

我正在使用 MVP 模式,不知道填充对象只是为了获取DataTable还是我可以快速使用静态存储库是最佳实践。正确的方法是什么?

在实现存储库设计模式之前,您应该首先知道我们为什么要实现它。 问题的答案是:

  • 最小化重复查询逻辑。
  • 将应用程序与持久性框架
  • (即实体框架(分离,以便您可以切换到新的持久性框架,而不会对主应用程序产生任何影响,因为所有更改都将保存在数据访问层上。
  • 提高可测试性(模拟数据将变得更加简单和容易(。

所以,现在让我们讨论实现: 实现存储库模式的正确方法是实现一个接口IProductRepository,该接口将包含将在ProductRepository中实现的方法的签名。此外,这是将其直接注入 IoC 容器所需的接口。 因此,您的IProductRepository应如下所示:

public interface IProductRepository
{
IEnumerable<Product> GetBillOfMaterialById(string productId);
}

您的ProductRepository应如下所示:

public class DeviceHistoryRepository : IDeviceHistoryRepository
{
public DeviceHistoryRepository(DbContext context)
{
Context = context;
}
public IEnumerable<Course> GetBillOfMaterialById(string productId)
{
return dbContext.Products.FirstOrDefault(p => p.ProductId == ProductId);
}
}

然后,从演示器中,您可以通过其构造函数注入存储库:

public class ProductPresenter: Presenter
{
#region Declaration
private readonly IProductRepository _productRepository;
#endregion
public ProductPresenter(IProductRepository productRepository)
{
#region Initialization
_productRepository = productRepository;
#endregion
}
}

然后,您可以从演示者的动作/方法访问它,如下所示:

Product product = _productRepository.GetBillOfMaterialById(productId);

标准方法是直接从该方法检索数据。这样,只有在您实际需要时才检索数据。

var productRepository = new ProductRepository();
DataTable billOfMaterial = productRepository.GetBillOfMaterial(productId);

由于可能存在并发问题,不使用静态存储库更安全。 如果使用的是 .NET Core,还可以通过依赖关系注入实现 ASP.NET Core(https://learn.microsoft.com/en-us/aspnet/core/fundamentals/repository-pattern?view=aspnetcore-2.1(存储库模式。

最新更新