How to abstract data context of entities in C #
In my application, I created a DAL with a repository class. The repository uses the EF class set as the Data Context .
I would like to create an abstraction to be able to use multiple Data contexts with the same repository . I am using the following code to initialize the context ( ProductEntities
is the EF context):
public class ProductRepository : IProductRepository
{
?type? _productEntitiesContext;
public productRepository()
{
_productEntitiesContext = new ProductEntities();
}
public productRepository(?type? productContext)
{
_productEntitiesContext = productContext;
}
}
But I don't know the type _productEntitiesContext
(s productContext
). ProductEntities
inherited from ObjectContext
.
To achieve abstraction I always use interfaces, I don't know if I can use ObjectContext
since this is a class.
Does anyone know if my goal is possible?
source to share
Not sure if the issue is hardcoding ProductEntities
here - ProductRepository
it seems to be a specific implementation of the product anyway.
If you want to push ProductEntities
into your repository without using dependencies, you can create a marker interface, for example IProductEntities
, and implement it inProductEntities
public interface IProductEntities { }
public partial class ProductEntities : IProductEntities { }
Remember, although it ProductEntities
is a generated class, you can still add code to it because its partial (as a side note, if it was not partial, you could just inherit it)
You might want to add some methods to the interface IProductEntities
if you're really thinking about switchable data contexts. Although, I doubt there is a need to switch context and I'm not sure who will provide an alternative implementation.
As such, the repository pattern abstracts data access anyway, so it sees no value in abstracting the EF context in this way. Tomorrow, if you want to use a different OR wrapper (like NHibernate), you can perhaps provide another implementation IProductRepository
that uses a different OR mapping file.
source to share
If, after a subsequent layer of abstract text, you can consider unit of work and IoC, there are many examples for stackoverflow. The linq-to-sql examples also apply to the Entity framework. I have personally implemented this on several projects using the Entity framework. If you are curious about unit of work and IoC in the links below.
DataContext, repositories and block of work
hope this helps.
source to share