带有实体框架的C#有没有办法用抽象基类实现存储库模式?

时间:2013-03-15 18:03:00

标签: c# entity-framework repository-pattern

我希望我的存储库继承自抽象类(Base Repository),而不是接口。我决定使用抽象类,因为我不会对存储库进行单元测试(我将单元测试服务层)而且我不想将相同的实现复制到从此基础存储库继承的每个存储库类

例如:

public abstract class BaseRepository<T> where T : class
{
    protected DbSet<T> dbSet;

    public BaseRepository(DbContext dataContext)
    {
        dbSet = dataContext.Set<T>();
    }

    public void Insert(T entity)
    {
        dbSet.Add(entity);
    }

    public IEnumerable<T> SearchFor(Expression<Func<T, bool>> predicate)
    {
        return dbSet.Where(predicate);
    }

    public IEnumerable<T> GetAll()
    {
        return dbSet;
    }

    public T GetById(int id)
    {
        return dbSet.Find(id);
    }
}

当我尝试创建从此基本存储库继承的其他存储库时,我遇到了构造函数的问题。如何将datacontext传递给这些派生类以便可以使用它们?

1 个答案:

答案 0 :(得分:3)

您需要在构造函数中传递上下文:

    public class Repository<TEntity> where TEntity : class
    {
        internal MyEntities context;
        internal DbSet<TEntity> dbSet;

        public Repository(MyEntities context)
        {
            this.context = context;
            this.dbSet = context.Set<TEntity>();
        }

        public virtual IEnumerable<TEntity> Get(
            Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            string includeProperties = "")
        {
            IQueryable<TEntity> query = dbSet;

            if (filter != null)
            {
                query = query.Where(filter);
            }

            foreach (var includeProperty in includeProperties.Split
                (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = query.Include(includeProperty);
            }

            if (orderBy != null)
            {
                return orderBy(query).ToList();
            }
            else
            {
                return query.ToList();
            }
        }

        public virtual TEntity GetByID(object id)
        {
            return dbSet.Find(id);
        }

        public virtual void Insert(TEntity entity)
        {
            dbSet.Add(entity);
        }

        public virtual void Delete(object id)
        {
            TEntity entityToDelete = dbSet.Find(id);
            Delete(entityToDelete);
        }

        public virtual void Delete(TEntity entityToDelete)
        {
            if (context.Entry(entityToDelete).State == EntityState.Detached)
            {
                dbSet.Attach(entityToDelete);
            }
            dbSet.Remove(entityToDelete);
        }

        public virtual void Update(TEntity entityToUpdate)
        {
            dbSet.Attach(entityToUpdate);
            context.Entry(entityToUpdate).State = EntityState.Modified;
        }
    }

使用:

var repo = new Repository<MyClass>(context);