2014-09-19 95 views
0

刪除具有關聯記錄的記錄時遇到問題。無法刪除包含子實體的實體

這是一個非常簡單的設置:「組件」可以有一個或多個(或沒有!)「componentProcesses」。如果刪除沒有進程的組件,則不會出現錯誤,並且組件已成功從數據庫中刪除。如果我刪除與處理的組件,然後我收到以下消息上調用manager.saveChanges():

The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_dbo.componentProcesses_dbo.components_ComponentID". The conflict occurred in database "mydb", table "dbo.components", column 'Id' 

的模式基本上是:

Public Class component 
    Public Property Id() As Integer 

    ...irrelevant fields removed.... 

    Public Overridable Property Processes() As ICollection(Of componentProcess)   
End Class 

Public Class componentProcess 
    Public Property Id() As Integer 

    ...irrelevant fields removed.... 

    Public Property ComponentID() As Integer 'process belongs to component 
    Public Property ProcessId() As Integer 'links to specific process 

    Public Overridable Property Component() As component 
    Public Overridable Property Process() As process 
End Class 

我不會顯示「組件」和「過程」模型,因爲它們只是簡單的基於id的靜態表。

當用戶刪除一個組件,代碼:

//editComponent is a ko.observable containing currently-being-edited component 

    //editComponent().processes().forEach(function (p) { 
    // p.entityAspect.setDeleted(); //sets to deleted but won't persist if save isn't called 
     //editComponent().processes.remove(function (_process) { 
     // return _process.id() == p.id() 
     //}); 
    //}); 

    editComponent().entityAspect.setDeleted(); //sets to deleted but won't persist if save isn't called 
    editComponent(null); //empty observable to trigger screen UI updates 

正如你可以從上面的代碼看,我已經和註釋掉各行,看看它是否會影響試驗結果,但它沒有。無論是否將每個孩子的「componentProcess」entityaspect設置爲「已刪除」,我在保存更改時都會遇到同樣的錯誤。

Cascadedelete處於這種關係,如果我刪除SQL企業管理器中的組件,所有子組件進程都會立即刪除,以便正常工作。

回答

1

SQL錯誤似乎與您聲稱數據庫關係設置爲級聯刪除不一致......儘管我無法解釋您在SQL Server Management Studio中如何擺脫它。

也許你可以跟蹤數據庫調用的順序?

我知道有什麼困擾你的嘗試刪除子進程:你正在改變editComponent.processes陣列,而你正在迭代它!這是一個禁忌。

每當您撥打setDeleted時,Breeze將從editComponent.processes數組中刪除Process實體。當迭代器迴繞時,它跳過下一個process

在調用setDeleted的內容之前,您需要複製數組。像這樣的東西應該這樣做:

// copy with slice() 
var processes = editComponent().processes().slice(); 
// iterate over the copy 
processes.forEach(function (p) { 
    // Breeze removes each `p` from its parent editComponent.processes array 
    p.entityAspect.setDeleted(); //marks deleted but won't persist until saveChanges is called 
}); 

expect(editComponent().processes().length).to.equal(0); 

HTH

+0

忘記關於這個問題,我被分心。只是測試應用程序,並摔倒了這個錯誤,並記得我問過這個問題。示例代碼完美工作。再次感謝病房,我明白你的意思。 – TheMook 2014-10-29 11:33:35