Repository pattern with EF Code First

北城余情 提交于 2019-12-13 06:16:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!