问题
I am not grasping something when creating my repository pattern with EF Code First. If I want to abstract out EF I would have to make my repository be of type IObjectContextAdapter, no? That is what DbContext implements. If I later switch to use something like NHibernate or some other 3rd party ORM, it may not implement IObjectContextAdapter.
Is my only solution to create a wrapper that wraps the ORM and does return an implementation of IObjectContextAdapter? If so, what is the point?
回答1:
I'm not sure you have to implement IObjectContextAdapter
when creating a repository pattern with EF. The main difference between using EF or something like NHibernate will be how to wrap either the DbContext
or the ISession
respectively.
Here is a sketch of how an EF code-first repository could be written:
public interface IRepository<TEntity>
{
void Save();
}
public class Repository<TEntity> : IRepository<TEntity>
{
private readonly IDbSet<TEntity> entitySet;
public Repository(DbContext context)
{
this.entitySet = context.Set<TEntity>();
}
public void Save()
{
return this.entitySet.SaveChanges();
}
}
This allows the actual DbContext
to be injected.
来源:https://stackoverflow.com/questions/16135676/repository-pattern-with-ef-code-first