且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

不完整的EF代码级联删除多对多关系

更新时间:2022-11-05 09:34:52

为了级联删除,要进行级联必须有一个外键返回到被删除的记录。所以在你的例子中,你删除一个联系人记录。因为他们是从ContactPhoneNumber到Contact的外键,所以级联起作用。由于PhoneNumber中没有外键到ContactPhoneNumber(外键按其他方式)级联不会继续。

In order for the cascading delete to work records that are going to be cascaded must have a foreign key back to the record being deleted. So in your example, You delete a Contact record. Because their is a foreign key from ContactPhoneNumber to Contact, the cascade works. Since there is no foreign key from PhoneNumber to ContactPhoneNumber, (the foreign key goes the other way) the cascade does not continue.

这是因为您将关系定义为多对多关系。如果您想要尝试在您的模型上执行级联删除,如果您希望删除一个ContactPhoneNumber,然后删除其关联的PhoneNumbers,那么现在可能会有其他没有有效PhoneNumber的ContactPhoneNumbers(因为可以许多ContactPhoneNumbers到一个PhoneNumber)。现在这些将需要删除,这个过程将继续下去。数据库不喜欢这个循环级联。

This is because you defined the relationship as a many to many. If you think about trying to perform a cascading delete on your model as you would like, If a ContactPhoneNumber is deleted and then its associated PhoneNumbers are deleted, there could now be other ContactPhoneNumbers that that don't have a valid PhoneNumber (Because there can be many ContactPhoneNumbers to one PhoneNumber). Now these would need to be deleted and this process would continue. Databases don't like this cyclical cascading.

我不清楚为什么你需要多对多的关系,如果你真的需要它,你将无法执行删除级联。如果您可以建立关系:

It is not entirely clear to me why you need the many to many relationship, If you truly need it you will not be able to perform a cascade on delete. If you can make your relationship:

1联系人 - * ContactPhoneNumber 1- * PhoneNumber,那么您可以将级联配置为您想要的工作。

1 Contact - * ContactPhoneNumber 1- * PhoneNumber, then you could configure the cascade to work like you want it too.