具有EF代码优先的存储库模式 [英] Repository pattern with EF Code First
问题描述
我唯一的解决方案是创建一个包装ORM的包装器,并返回一个IObjectContextAdapter的实现?
我不确定你必须实现 IObjectContextAdapter
当使用EF创建存储库模式。使用EF或像NHibernate这样的东西的主要区别是如何分别包含 DbContext
或 ISession
/ p>
以下是EF代码第一个存储库如何编写的草图:
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();
}
}
这允许实际的 DbContext
注入。
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?
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.
这篇关于具有EF代码优先的存储库模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!