c# - 如何在 C# 中抽象实体数据上下文

标签 c# repository datacontext abstraction

在我的应用程序中,我创建了一个带有 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/

相关文章:

c# - 如何在 C# 中将 Wpf BitmapSource 转换为 byte[]

c# - IO操作的并发问题

eclipse - 为Eclipse中的项目添加Maven存储库?

c# - 更改 DataContext 并绑定(bind) ItemsSource 和 SelectedItem 时 WPF 中 ComboBox 的奇怪行为(或错误?)

c# - wpf如何绑定(bind)到存在的DataContext?

c# - 在 C# 中使用 AS 时出现异常

c# - 关于集合返回类型的问题

programming-languages - 按编程语言列出的顶级存储库

php - 无法让 Composer "path"存储库工作

entity-framework - .CreateObjectSet<T>、.Set<T> 和 .CreateQuery<T> 之间的区别?