级联删除、同表、Entity Framework 4 Code First
您好,我目前正在使用 .sdf 数据库(Server Compact Version 4.0)和 sql express。我正在尝试在同一个表(类别 - 子类别)上设置级联删除,但我发现我无法添加与同一个表的关系。
外键约束有并且 更新或删除级联规则,以及 自引用同一列中的列 表,不允许
我该怎么办?
编辑
只有我一个人有这个问题吗?
Hi Im currently working with .sdf database (Server Compact Version 4.0) and sql express. I'm trying to setup a cascade delete on a same table (category - sub category) but I get that I cant add relation to the same table.
A foreign key constraint had and
update or a delete cascade rule, and
self-references a column in the same
table, is not allowed
What can I do about this?
EDIT
I'm the only one with this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如您的 SQLException 所建议的,这是 SQL Server 的一般限制,与 EF 或 Code First 无关。基本上,当级联路径从表 A 中的列 col1 到表 A 中的列 col2 时,SQL Server 不允许在内部关系上创建级联操作。A->A。
事实上,Code First 试图使用声明性引用完整性 (DRI) 来强制执行级联删除和 SQL Server 抛出。
对此关系强制执行级联删除的唯一方法是使用触发器。您可以在类别表上编写一个删除触发器,删除相关行或将所有相应的外键设置为 NULL(根据您的要求)。
As your SQLException suggested, this is a limitation of SQL Server in general and has nothing to do with EF or Code First. Basically, SQL Server does not allow creating cascade actions on Inner relationships – when the cascade path goes from column col1 in table A to column col2 also in table A. A->A.
In fact, Code First was trying to use Declarative Referential Integrity (DRI) to enforce cascade deletes and SQL Server throws.
The only way to enforce cascade deletes for this relationship is to use Triggers. You can write a Delete Trigger on the category table that either deletes the dependent rows or sets all corresponding foreign keys to NULL (based on your requirements).