全局禁用 EF Core 2 上的级联删除

问题描述 投票:0回答:4

我需要了解全局禁用

EF Core 2
中的级联删除的方法。任何帮助都适用。

在 EF 6.x 中,我们使用以下代码禁用

OneToMany
ManyToMany
关系上的级联删除:

builder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
builder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
entity-framework entity-framework-core
4个回答
100
投票

不幸的是,EF Core 目前(目前最新的是 v2.0)没有公开一种全局控制约定的好方法。

默认的 EF Core 2.0 约定是使用

DeleteBehavior.Cascade
表示必需关系,使用
DeleteBehavior.ClientSetNull
表示可选关系。我可以建议的解决方法是在
OnModelCreating
覆盖结束时使用典型的元数据模型循环。在这种情况下,找到所有已经发现的关系并相应地修改它们:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // ...

    var cascadeFKs = modelBuilder.Model.GetEntityTypes()
        .SelectMany(t => t.GetForeignKeys())
        .Where(fk => !fk.IsOwnership && fk.DeleteBehavior == DeleteBehavior.Cascade);

    foreach (var fk in cascadeFKs)
        fk.DeleteBehavior = DeleteBehavior.Restrict;

    base.OnModelCreating(modelBuilder);
}

0
投票
constraints: table =>
                {
                    table.PrimaryKey("PK_ComandaPlato", x => x.ComandaPlatoId);
                    table.ForeignKey(
                        name: "FK_ComandaPlato_Comanda_ComandaId",
                        column: x => x.ComandaId,
                        principalTable: "Comanda",
                        principalColumn: "ComandaId",
                        onDelete: ReferentialAction.Cascade);//default: cascade on
                    table.ForeignKey(
                        name: "FK_ComandaPlato_Plato_PlatoId",
                        column: x => x.PlatoId,
                        principalTable: "Plato",
                        principalColumn: "PlatoId",
                        onDelete: ReferentialAction.NoAction);//turn off cascade,"by hand"
                });
//comments: modifing the auto-generated migration, "harcode by hand" this attibute, as view bellow: change "Cascade" to "NoAction" (as view 1st and 2st examples)

0
投票

我能够在 EF Core 7 中使用以下代码在我的

DbContext
类型上禁用“级联删除”约定:

protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
    configurationBuilder.Conventions.Remove(typeof(CascadeDeleteConvention));
    configurationBuilder.Conventions.Remove(typeof(SqlServerOnDeleteConvention));
}

希望这对任何人都有用。


-3
投票

也许有帮助:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
ChangeTracker.CascadeDeleteTiming = ChangeTracking.CascadeTiming.Never;
ChangeTracker.DeleteOrphansTiming = ChangeTracking.CascadeTiming.Never;
}
© www.soinside.com 2019 - 2024. All rights reserved.