在我的应用程序中,我创建了一个带有 Repository 类的 DAL。存储库使用一组 EF 类作为数据上下文。
我想创建一个抽象,以便能够将多个数据上下文与相同的存储库一起使用。我使用以下代码初始化上下文(ProductEntities
是 EF 上下文):
public class ProductRepository : IProductRepository
{
?type? _productEntitiesContext;
public productRepository()
{
_productEntitiesContext = new ProductEntities();
}
public productRepository(?type? productContext)
{
_productEntitiesContext = productContext;
}
}
但我不知道 _productEntitiesContext
(和 productContext
)的类型。 ProductEntities
继承自 ObjectContext
。
为了实现抽象,我总是使用接口(interface),我不知道我是否可以使用 ObjectContext
因为它是一个类。
有人知道我的目标是否可以实现吗?
最佳答案
是这样的吗?
public class ProductRepository<T> : IProductRepository where T: new()
{
T _productEntitiesContext;
public productRepository()
{
_productEntitiesContext = new T();
}
public productRepository(T productContext)
{
_productEntitiesContext = productContext;
}
}
关于c# - 如何在 C# 中抽象实体数据上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9871925/