0
我在從3個嵌套表中刪除時遇到問題。從嵌套表中刪除記錄MVC 5
當我試圖從第一個表中刪除一條記錄,它給了我一個錯誤
System.Data.SqlClient.SqlException: The DELETE statement conflicted with the REFERENCE constraint
delete操作方法是:
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Parent parent = db.Parent.FirstOrDefault(t => t.ParentID == id);
foreach(var item in parent.Child.ToList())
{
db.Child.Remove(item);
foreach (var grand in item.Grand.ToList())
{
db.Grand.Remove(grand);
}
}
db.Parent.Remove(parent);
db.SaveChanges();
return RedirectToAction("Index");
}
我真的很感激任何幫助,在這個問題上 另外,如果有人可以指導我對嵌套表的CRUD操作教程,這將幫助我很多。
首先,您需要從問題表中刪除記錄,因爲您在問題表中添加了FK,這就是爲什麼您不能刪除主鍵直到刪除包含FK的所有記錄。 –
您正試圖刪除其他表中引用的數據:您無法這樣做。刪除約束,刪除數據並重新創建約束,或者首先刪除由外鍵引用的數據。 (FK表示外鍵,這是你的錯誤信息) – Hyarantar
對不起,我是新手。如果可以提供一個例子,我會很感激。 – Eyad