2011-08-23 103 views
2

我試圖通過實體框架(MySQL /連接器)刪除具有外鍵關係的對象。MySQL +實體框架:無法刪除對象

ClientAccount >>> ClientEmailAddresses

foreach (ClientAccount client in recsClientStore.Deleted) { 
     ClientAccount stub = new ClientAccount(); 
     stub.Id = client.Id; 
     this.DBContext.AttachTo("ClientAccounts", stub); 


     stub.FkClientEmailAddresses.Clear(); 
     this.DBContext.DeleteObject(stub); 
    } 

    this.DBContext.SaveChanges(); 

..但是,當我這樣做,我得到了以下錯誤:

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.

我真的不知道這個地方給我留下。我必須先刪除EmailAddress對象嗎?我們對開啓級聯很謹慎,但看起來越來越像這是整理外鍵所必需的。

回答

2

的問題是這樣的:

stub.FkClientEmailAddresses.Clear(); 

不會刪除關係。它只在相關實體中設置FK爲空。如果你希望他們真正刪除您必須:

  • 致電Remove他們的目標設定
  • 變化關係identifying relationship刪除它們 - 這將使Clear按預期方式工作
  • 正確設置級聯兩個EDMX刪除和數據庫,並且根本不叫清除
+0

謝謝。我想我們將重新審視我們的結構,以確定我們是否真的需要級聯。 – pierre