作者:孩子气zyj2 | 来源:互联网 | 2022-12-03 14:45
我有一个被调用的对象Product
,我想从所有产品列表中检索某个产品的"物料清单"(存储在SQL Server中).我应该先创建Product对象,然后通过方法从我的存储库中获取数据,如下所示:
var productId = "1";
Product product = new Product(productId);
DataTable billOfMaterial = product.GetBillOfMaterial();
或者从静态存储库检索数据strait,如下所示:
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
或者我是否可以快速使用静态存储库.这样做的正确方法是什么?
1> Mohamed Kame..:
在实现存储库设计模式之前,您应该首先知道我们为什么要实现它.这个问题的答案是:
最小化重复的查询逻辑.
将应用程序与持久性框架(即实体框架...)分离,以便您可以切换到新的持久性框架,而不会对主应用程序产生任何影响,因为所有更改都将保留在数据访问层上.
提升可测试性(模拟数据将更简单,更容易).
所以,现在让我们讨论一下实现:实现存储库模式的正确方法是实现一个接口IProductRepository
,该接口将包含将在您的实现中实现的方法的签名ProductRepository
.此外,这是您需要的接口,以便将其直接注入IoC容器.所以,你IProductRepository
应该看起来像这样:
public interface IProductRepository
{
IEnumerable GetBillOfMaterialById(string productId);
}
你ProductRepository
应该看起来像这样:
public class DeviceHistoryRepository : IDeviceHistoryRepository
{
public DeviceHistoryRepository(DbContext context)
{
COntext= context;
}
public IEnumerable 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
}
}
然后,您可以从Presenter的操作/方法中访问它,如下所示:
Product product = _productRepository.GetBillOfMaterialById(productId);