2012-11-22 72 views
4

我在我的模型如何在實體框架中級聯刪除?

汽車和carPart

與1兩個對象:N的關係。

我想刪除級聯實體車。 當我刪除我得到以下異常:

The operation failed: The relationship could not be changed because one or 
more of the foreign-key properties is non-nullable. When a change is made 
to a relationship, the related foreign-key property is set to a null value. 
If the foreign-key does not support null values, a new relationship must 
be defined, the foreign-key property must be assigned another non-null value, 
or the unrelated object must be deleted. 

我認爲它會嘗試先刪除該汽車對象中的汽車零部件。
由於外鍵,這是不可能的。

我該如何處理?
我想要的,顯然是先刪除carPart,然後再刪除車。
謝謝。

回答

6

你需要告訴數據庫,你想級聯刪除,然後實體框架將做你的期望。如果你去Relationships屏幕在SQL Server Management Studio中的一個表,你可以改變FK行爲:

Cascade delete in Sql Server Management Studio

+0

感謝這個答案! –

1

如果您想級聯刪除,然後在數據庫級別設置級聯刪除。您收到錯誤,因爲SQL不允許刪除。

你不必在實體框架中做到這一點。