存储库模式使用实体框架,代码优先和CRUD操作

时间:2014-09-01 15:22:11

标签: c# asp.net-mvc entity-framework repository-pattern data-access-layer

我试图对如何正确实现存储库模式有一个实际的了解。我在我的MVC Web应用程序中创建了一个名为Employees的模型类,iv创建了一个上下文类和一个连接字符串来生成数据库。我还使用实体框架工作创建了一个带有读/写操作的控制器,它带来了一些CRUD操作,如Update,Delete等。

如果我正确理解了存储库模式,我应该将所有数据访问逻辑放在存储库中。我还认为我需要为上下文类创建一个IRepository接口来继承。

在我的控制器中,我有这些基本的CRUD操作。在我的情况下,是否应将这些操作方法中的所有逻辑移动到我的存储库类?

控制器:

public class EmployeeController : Controller
{
    private _dbCrudApplicationContext db = new _dbCrudApplicationContext();

    // GET: Employee
    public ActionResult Index()
    {
        return View(db.Employees.ToList());
    }

    // GET: Employee/Details/5
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Employee employee = db.Employees.Find(id);
        if (employee == null)
        {
            return HttpNotFound();
        }
        return View(employee);
    }

    // GET: Employee/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: Employee/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,FirstName,LastName,EmployeeNumber,Department,HasValidEmployeeCertificate")] Employee employee)
    {
        if (ModelState.IsValid)
        {
            db.Employees.Add(employee);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(employee);
    }

    // GET: Employee/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Employee employee = db.Employees.Find(id);
        if (employee == null)
        {
            return HttpNotFound();
        }
        return View(employee);
    }

    // POST: Employee/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "Id,FirstName,LastName,EmployeeNumber,Department,HasValidEmployeeCertificate")] Employee employee)
    {
        if (ModelState.IsValid)
        {
            db.Entry(employee).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(employee);
    }

    // GET: Employee/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Employee employee = db.Employees.Find(id);
        if (employee == null)
        {
            return HttpNotFound();
        }
        return View(employee);
    }

    // POST: Employee/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Employee employee = db.Employees.Find(id);
        db.Employees.Remove(employee);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

我开始添加"索引"存储库的方法,但我不确定如何实现其他方法,因为它们更复杂。我应该在Controller中的动作方法中移动所有逻辑还是只移动部分代码?

存储库:

public class CustomerRepository : _dbCrudApplicationContext
{
    _dbCrudApplicationContext db = new _dbCrudApplicationContext();


    public List<Employee> GetAllEmployees()
    {
        return db.Employees.ToList();    
    }
}

1 个答案:

答案 0 :(得分:0)

存储库不应该尝试扩展模型上下文,而应该使用此上下文来执行某些操作。存储库定义为

  
    
      

存储库在域和数据映射层之间进行调解,其作用类似于内存中的域对象集合。客户端对象以声明方式构造查询规范,并将它们提交给Repository以满足要求。对象可以添加到存储库中,也可以从存储库中删除,因为它们可以从简单的对象集合中获取,并且存储库封装的映射代码将在后台执行适当的操作

    
  

界面风格背后的主要原因是允许进行单元测试。

在您的情况下,存储库可能看起来像

public interface ICustomerRepository
{
   public List<Employee> GetAllEmployees();
}

public class CustomerRepository : ICustomerRepository
{
   private _dbCrudApplicationContext db;

   public CustomerRepository(_dbCrudApplicationContext context)
   {
     db = context;
   }

   public List<Employee> GetAllEmployees()
   {
      return db.Employees.ToList();
   }
}

完成后的存储库应包含要在模型上执行的所有操作。这些将需要从MVC视图中迁移。

有关详细信息,请参阅http://blog.gauffin.org/2013/01/repository-pattern-done-right/