具有EF代码优先的存储库模式 [英] Repository pattern with EF Code First

查看:159
本文介绍了具有EF代码优先的存储库模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用EF Code First创建我的存储库模式时,我并没有抓住什么。如果我想抽出EF,我必须使我的存储库类型为IObjectContextAdapter,否?那就是DbContext实现的。如果我以后切换使用像NHibernate或其他第三方ORM这样的东西,那么它可能不会实现IObjectContextAdapter。



我唯一的解决方案是创建一个包装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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆