多对多关系中的多个级联删除路径 (EF 4.1)
表:
Shop
Product
Category
关系:
(Shop) 1 <---> n (Categories)
(Shop) 1 <---> n (Products)
(Categories) n <---> n (Products)
级联删除:
Shop ---> Categories ... I defined this using fluent API
Shop ---> Products ... I defined this using fluent API
Categories <---> Products ... EF 4.1 automatically defines cascade for "Category_Product" join table
问题: 以上导致“多个”级联删除路径异常。
潜在的修复:
- 删除ManyToManyConvention,但这意味着我必须手动对系统中的每个连接表执行删除,这是不切实际的。
- 我可以从商店->类别或商店->产品中删除级联删除。但那时我可能会有很多孤立的记录。
你们如何处理这个问题?
谢谢
THE TABLES:
Shop
Product
Category
THE RELATIONSHIPS:
(Shop) 1 <---> n (Categories)
(Shop) 1 <---> n (Products)
(Categories) n <---> n (Products)
THE CASCADE DELETES:
Shop ---> Categories ... I defined this using fluent API
Shop ---> Products ... I defined this using fluent API
Categories <---> Products ... EF 4.1 automatically defines cascade for "Category_Product" join table
THE PROBLEM:
Above results in a "multiple" cascade deletion path exception.
POTENTIAL FIXES:
- Remove the ManyToManyConvention, but that means I must manually perform deletes for every join table in the system, which is impractical.
- I can remove the cascade delete from Shop->Category or Shop->Products. But then I'll probably have lots of orphaned records.
How are you folks dealing with this problem?
THANKS
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不是实体框架的问题,而是SQL Server的问题。我不认为异常实际上意味着循环级联删除。更可能意味着多个级联删除路径,因为连接表记录可以从类别和产品端删除,因为从商店级联。 SQL Server 不允许这样做,因为它需要一些更复杂(且更慢)的算法来正确计算级联时哪些记录以及何时必须删除。
简而言之,您必须打破这一点,这实际上意味着您必须在删除商店之前手动删除所有相关记录(类别或产品)。这将需要存储过程(或直接 SQL DELETE 命令),否则您必须先加载所有它们,然后将它们一一删除。
编辑:
正如您在评论中指出的,这也可以通过添加 BEFORE DELETE 触发器来解决,该触发器将删除相关记录(如果存在作为一个级联路径的替换)。
This is not a problem of entity framework but the problem of SQL server. I don't think that exception actually means circular cascade delete. It more probably means multiple cascade delete paths because join table records can be deleted from both categories and products side because of cascading from shop. SQL server doesn't allow this because it requires some more complex (and slow) algorithms to correctly compute which records and when have to be deleted when cascading.
Simply you must break this and it will really mean that you will have to manually delete all related records (either categories or products) before you delete shop. This will require stored procedure (or direct SQL DELETE command) otherwise you will have to load all of them first and delete them one by one.
Edit:
As you pointed in the comment this can be also solved by adding BEFORE DELETE trigger which will delete related records if exists as replacement of one cascade path.