无法删除包含子实体的实体
问题描述:
删除具有关联记录的记录时遇到问题。无法删除包含子实体的实体
这是一个非常简单的设置:“组件”可以有一个或多个(或没有!)“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企业管理器中的组件,所有子组件进程都会立即删除,以便正常工作。
答
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
忘记关于这个问题,我被分心。只是测试应用程序,并摔倒了这个错误,并记得我问过这个问题。示例代码完美工作。再次感谢病房,我明白你的意思。 – TheMook 2014-10-29 11:33:35