0

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

例如:

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);
    }
}

当我尝试创建从该基础存储库继承的其他存储库时,构造函数出现问题。如何将数据上下文传递到这些派生类中以便可以使用它们?

4

1 回答 1

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);
于 2013-03-15T18:43:43.507 回答