1
在我的數據庫模型中,我有4個實體:Order,Service,Client,Employee。 他們的關係:刪除實體框架中的孩子
客戶0..1 - *訂購
訂購1 - *服務
員工1 - *服務。
我試圖刪除特定的順序所有服務,但我得到一個InvalidOperationException: 操作失敗:關係不能被改變,因爲一個或多個外鍵的屬性是不可爲空。當對關係進行更改時,相關的外鍵屬性將設置爲空值。如果外鍵不支持空值,則必須定義新的關係,必須爲外鍵屬性指定另一個非空值,或者必須刪除不相關的對象。
這裏是我的代碼:
public static void ClearSevicesInOrder(int orderId)
{
using (DbEntities context = new DbEntities())
{
var o = context.Orders.Find(orderId);
o.Services.Clear();
context.SaveChanges();
}
}
我該怎麼辦錯了嗎?
感謝事先刪除每一個服務! 我的代碼: foreach(var item in context.Services.Where(s => s.OrderID == orderId)) { context.Services.Remove(item); } context.SaveChanges(); –