多对多关系中的多个级联删除路径 (EF 4.1)

发布于 2024-11-08 21:12:03 字数 800 浏览 11 评论 0原文

表:

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

问题: 以上导致“多个”级联删除路径异常。

潜在的修复:

  1. 删除ManyToManyConvention,但这意味着我必须手动对系统中的每个连接表执行删除,这是不切实际的。
  2. 我可以从商店->类别或商店->产品中删除级联删除。但那时我可能会有很多孤立的记录。

你们如何处理这个问题?

谢谢

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:

  1. Remove the ManyToManyConvention, but that means I must manually perform deletes for every join table in the system, which is impractical.
  2. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

很糊涂小朋友 2024-11-15 21:12:03

这不是实体框架的问题,而是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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文