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

What is the proper way to implement the Repository Pattern ? and How to use it ?

我有一个名为 Product 的对象,我想从所有产品列表(存储在 SQL 服务器中)中检索某个产品的 "Bill Of Material"。我是否应该先创建 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);

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

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

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

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

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

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

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

  • 最大限度地减少重复查询逻辑。
  • 将您的应用程序与持久性框架分离(即 Entity Framework..),以便您可以切换到新的持久性框架而不会对您的主应用程序产生任何影响,因为所有更改都将保留在数据访问上图层.
  • 提升可测试性(模拟数据将变得更加简单和容易)。

那么,现在让我们讨论实现: 实现存储库模式的正确方法是实现一个接口 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);
    }
}

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

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);