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

标签 c# design-patterns repository-pattern mvp

<分区>

我有一个名为 Product 的对象,我想从所有产品(存储在 SQL Server 中)的列表中检索特定产品的“ Material list ”。我是否应该先创建 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 是否是最佳实践,或者我是否可以快速使用静态存储库。正确的做法是什么?

最佳答案

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

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

那么,现在让我们讨论实现: 实现存储库模式的正确方法是实现一个接口(interface) IProductRepository,它包含将在您的 ProductRepository 中实现的方法的签名。此外,这是将其直接注入(inject) IoC 容器所需的接口(interface)。 因此,您的 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 中,您可以通过其构造函数注入(inject)您的存储库:

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

然后您可以像这样从 Presenter 的 Actions/Methods 访问它:

Product product = _productRepository.GetBillOfMaterialById(productId);

关于c# - 实现存储库模式的正确方法是什么?以及如何使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52574374/

相关文章:

c# - Entity Framework 中实体的内部访问使得查询崩溃时的简单 linq

c# - WPF - 将 UserControl 可见性绑定(bind)到属性

html - 显示非常宽的表格的策略

data-structures - 存储库模式与 "smart"业务对象

c# - Entity Framework 是存储库吗

asp.net - 存储库模式最佳实践

c# - 我如何通过带有反射 C# 的属性获取类信息

c# - 如何在Windows窗体中制作YouTube视频流播放器?

.net - 当 View 不与模型交互时,它是 MVC 吗?

php - 多个服务层和数据库事务