c# - 实施存储库模式的正确方法是什么?以及如何使用它?
问题描述
我有一个名为的对象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);
}
}
然后从您的 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);
推荐阅读
- iis - IIS 应用程序池创建文件夹,其中包含 applicationhost.config
- c# - 如果我创建一个临时文件并非常频繁地修改它,这会给磁盘带来负担吗?
- linux - 守护进程与进程
- python - 类型对象“问题”没有属性“对象”
- google-sheets - Google 表格 - 如何制作调用宏的单元格?
- c# - 表单打开时允许输入设置货币的文本框
- character-encoding - 如何在 Spyder iPython 控制台中显示日文字符?
- php - 在 foreach 循环问题中使用 preg_replace
- php - 多个 AJAX 调用 - 第一次获取数据并转换为 JSON 对象,第二次更新 $_SESSION 信息
- c# - 获取.net中选中的单选按钮列表