gpt4 book ai didi

entity-framework - Entity Framework 是否支持删除记录并将外键设置为空?

转载 作者:行者123 更新时间:2023-12-03 07:24:58 24 4
gpt4 key购买 nike

我有一个这样的模型:

public class Account
{
public int Id { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
public Account Parent { get; set; }
}

我添加以下配置:

    this.HasOptional(item => item.Parent)
.WithMany()
.HasForeignKey(item => item.ParentId)
.WillCascadeOnDelete(true);

然后我收到以下错误消息:

Assembly Initialization method UnitTest.Biz.Accounting.TestInitializer.Init threw exception. System.Data.SqlClient.SqlException: System.Data.SqlClient.SqlException: Introducing FOREIGN KEY constraint 'FK_dbo.acct_Account_dbo.acct_Account_ParentId' on table 'acct_Account' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint.

我已经阅读了 EF 的文档,但我不明白我的代码哪里出了问题...

If a foreign key on the dependent entity is nullable, Code First does not set cascade delete on the relationship, and when the principal is deleted the foreign key will be set to null http://msdn.microsoft.com/en-us/data/jj591620#CascadeDelete

最佳答案

自引用表

SQL Server不允许自引用表进行级联删除。

As you can see, SQL Server noticed that your cascade operation is cyclic, and it does not allow this type of cascading. This is true not only for a self-referencing table, but also for any chain of relationships between tables in which the cascading operations have a potential to be cyclical.

Source

这就是为什么在 EF 中无法对自引用实体设置级联删除。

.WillCascadeOnDelete(true); // Not allowed.

如果依赖实体上的外键可为空,则 Code First 会这样做未对关系设置级联删除

关于default convention EF 的,您可以通过 Fluent api 覆盖它。如果您有以下代码,

public int? ParentId { get; set; } // <--- nullable
public Account Parent { get; set; }

EF默认会将级联删除标记为false,即使你没有配置WillCascadeOnDelete(false),这实际上意味着会设置数据库中的外键级联删除为删除时无操作

目前 EF 不支持 ON DELETE SET NULL 除非您有自定义查询来删除并重新添加约束,请检查 this post .

当删除主体时,外键将设置为空。

这已在 this post 中进行了解释这意味着仅当子级加载到上下文中时。

关于entity-framework - Entity Framework 是否支持删除记录并将外键设置为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25056031/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com