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

时间:2017-10-02 13:15:11

标签: entity-framework entity-framework-core

我需要了解全局禁用EF Core 2级联删除的方法。任何帮助都是适当的。

在EF 6.x中,我们使用以下代码禁用OneToManyManyToMany个字段上的级联删除:

builder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
builder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

3 个答案:

答案 0 :(得分:41)

不幸的是,EF Core目前(最新版本为v2.0)并没有提供一种控制全局约定的好方法。

默认的EF Core 2.0约定是使用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); } 覆盖结束时的典型元数据模型循环。在这种情况下,找到所有已发现的关系并相应地修改它们:

{{1}}

答案 1 :(得分: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)

答案 2 :(得分:-1)

可能有帮助:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
ChangeTracker.CascadeDeleteTiming = ChangeTracking.CascadeTiming.Never;
ChangeTracker.DeleteOrphansTiming = ChangeTracking.CascadeTiming.Never;
}