步骤11:最后我们来看删除数据。同样,我们先要取得要删除的数据,然后再删除。跟上面说的步骤类似,增加一个delete的脚手架视图,如下图:

修改控制层的代码如下:
// GET: /Customer/Delete/5
public ActionResult Delete(int id)
{
using (var databaseContext = new Models.MyDataContext())
{
return View(databaseContext.Customer.Find(id));
}
}
//
// POST: /Customer/Delete/5
[HttpPost]
public ActionResult Delete(int id,Models.Customer customer)
{
try
{
using (var databaseContext = new Models.MyDataContext())
{
databaseContext.Entry(databaseContext.Customer.Find(id)).State = System.Data.EntityState.Deleted;
databaseContext.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
public ActionResult Delete(int id)
{
using (var databaseContext = new Models.MyDataContext())
{
return View(databaseContext.Customer.Find(id));
}
}
//
// POST: /Customer/Delete/5
[HttpPost]
public ActionResult Delete(int id,Models.Customer customer)
{
try
{
using (var databaseContext = new Models.MyDataContext())
{
databaseContext.Entry(databaseContext.Customer.Find(id)).State = System.Data.EntityState.Deleted;
databaseContext.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
在方法Delete(int id)中,我们获得了数据库中要删除的数据记录,而真正删除的方法是在Delete(int id,Models.Customer customer)中,同样也是设置state状态后,再用SaveChanges()方法保存。