首页 > 解决方案 > 实施存储库模式的正确方法是什么?以及如何使用它?

问题描述

我有一个名为的对象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或者我是否可以快速使用静态存储库。正确的方法是什么?

标签: c#design-patternsrepository-patternmvp

解决方案


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

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

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

推荐阅读