我在我的數據庫中這兩個表,命名爲供應商和VendorPriceBreaks:刪除多個記錄相關表
Vendors
-----------------
VendorID (PK)
Name
VendorPriceBreaks
-----------------
VendorPriceBreakID (PK)
VendorID (FK)
Price
當我刪除供應商,我想有它刪除相關的所有VendorPriceBreaks以及。我正在使用實體框架。
我想這第一:
public RedirectToRouteResult Delete(int id)
{
MyEntities entities = new MyEntities();
var vendor = entities.Vendors.FirstOrDefault(v => v.VendorID == id);
entities.Vendors.Context.DeleteObject(vendor);
entities.Vendors.Context.SaveChanges();
return RedirectToAction("Index");
}
這給了我錯誤消息:DELETE語句衝突與基準約束「FK_VendorPriceBreaks_Vendors」
於是我就加入這行我刪除之前我object:vendor.VendorPriceBreaks.Clear();
但是後來我得到了這個錯誤信息:操作失敗:關係不可能b因爲一個或多個外鍵屬性是不可空的,所以改變了。當對關係進行更改時,相關的外鍵屬性將設置爲空值。如果外鍵不支持空值,則必須定義新的關係,必須爲外鍵屬性指定另一個非空值,或者必須刪除不相關的對象。
這樣做的最佳方式是什麼?
刪除的順序應該顛倒。您必須先刪除相關記錄,然後才能刪除父記錄。 – 2011-04-10 22:08:30
uppss :)我知道,很抱歉 – Bilgehan 2011-04-10 22:29:43