[英]DeleteOnSubmit() and SubmitChanges() don't work. No exception or error. InsertOnSubmit() works fine
I got this code to Delete a Category row from a Database. 我得到了这段代码来从数据库中删除“类别”行。 The Category has only 2 columns: Id and Name.
类别只有两列:ID和Name。 It doesn't announce any errors.
它不会宣布任何错误。 It just doesn't work.
就是行不通。
If it worked, it should Redirect to Categories/Index
. 如果有效,则应重定向到
Categories/Index
。 Instead, it shows Categories/Delete
but now without any Category as parameter. 而是显示
Categories/Delete
但现在没有任何类别作为参数。
public ActionResult Delete(int id)
{
var category = db.Categories.Where(r => r.Id == id).SingleOrDefault();
return View(category);
}
[HttpPost]
public ActionResult Delete(Category category)
{
try
{
Category c = db.Categories
.Where(r => r.Id == category.Id)
.Single<Category>();
db.Categories.DeleteOnSubmit(c);
db.SubmitChanges();
return RedirectToAction("Index");
}
catch
{
return View(category);
}
}
But this code for the Create action works just fine: 但是,用于Create操作的此代码可以正常工作:
public ActionResult Create()
{
Category c = new Category();
return View(c);
}
[HttpPost]
public ActionResult Create(Category category)
{
try
{
Category x = new Category
{
Name = category.Name
};
db.Categories.InsertOnSubmit(x);
db.SubmitChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Turns out the row I wanted to test the Delete functionality on was referenced as a foreign key by another table in the database. 原来我要测试删除功能的行被数据库中的另一个表引用为外键。
I tested deleting a row that was not referenced by any other table. 我测试了删除没有任何其他表引用的行。 Works just fine.
效果很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.