【问题标题】:Trying to understand Repository Pattern with EF6尝试使用 EF6 理解存储库模式
【发布时间】:2016-06-18 11:38:56
【问题描述】:

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

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

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

我的项目分层为:

  • 演示文稿
  • 业务层
  • 业务对象
  • 数据访问层
  • 网络服务

    在 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 个左右的表。

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

    我得到了错误 “MyEFConn”是一个“类型”,但用作“变量”

    我实现它的尝试是:

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

    MyEFConn 是我的 DbContext 类..

    public partial class MyEFConn: DbContext
    
  • 【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    我收到错误消息“MyEFConn”是一个“类型”但被用作“变量”

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

    例如:

    MyEfConn context = new MyEfConn();
    MyRepository<MyUsers> users = new MyRepository<MyUsers>(context);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多