尝试使用EF6了解存储库模式

时间:2016-03-04 16:26:38

标签: c# entity-framework

我目前正在实施EF6来替换当前存在的ADO连接。

我读过有关为什么我应该/不应该使用存储库模式的文章。

但是我仍然不确定如何正确调用存储库模式。

我的项目分层为:

  • 演示
  • 业务层
  • Business Objects
  • 数据访问层
  • 网络服务

    在DAL中,我将EF6连接添加到我的数据库。 我创建了一个IRepository和Repository类。

    业务层应该是调用Repository类的吗? 如果是这样,我在这里错过了如何调用它的连接。

    存储库类:

    public class MyRepository<T> : IRepository<T> where T : class 
    {
        protected DbSet<T> DbSet;
        protected DbContext _context;
    
        public MyRepository(DbContext dataContext)
        {
            _context = dataContext;
            DbSet = dataContext.Set<T>();
        }
    
        #region IRepository
    
        public int Save()
        {
            return _context.SaveChanges();
        }
    
        public void Insert(T entity)
        {
            DbSet.Add(entity);
        }
    
        public void Delete(T entity)
        {
            DbSet.Remove(entity);
        }
    
        public IQueryable<T> SearchFor(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
        {
            return DbSet.Where(predicate);
        }
    
        public IQueryable<T> GetAll()
        {
            return DbSet;
        }
    
        public T GetById(int id)
        {
            return DbSet.Find(id);
        } 
        #endregion
    }
    

    我的目标是让MyRepository处理我在EF中添加的6个左右的表。

    我缺少的是如何在我的业务访问层中实现此类。

    我收到错误 &#39; MyEFConn&#39;是一种&#39;类型&#39;但用作变量&#39;

    我实现它的尝试是:

    MyRepository<"table from EF"> users = new MyRepository<"table from EF">(MyEFConn);
    

    MyEFConn是我的DbContext类..

    public partial class MyEFConn: DbContext
    
  • 1 个答案:

    答案 0 :(得分:2)

      

    我收到错误'MyEFConn'是'type'但是像'变量'一样使用

    这是因为MyRepository的构造函数希望传递一个DbContext的实例。在您的情况下,这将是MyEFConn的实例。

    例如:

    MyEfConn context = new MyEfConn();
    MyRepository<MyUsers> users = new MyRepository<MyUsers>(context);
    
    相关问题