Disable cascading deletion on EF Core 2 globally

I need to know about ways to disable cascading deletion in EF Core 2 around the world. Any help is appreciated.

In EF 6.x, we used the following code to disable cascading deletion for both OneToMany and ManyToMany realtions:

 builder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); builder.Conventions.Remove<ManyToManyCascadeDeleteConvention>(); 
+5
source share
1 answer

Unfortunately, EF Core currently (the latest currently v2.0) does not provide a good way to manage agreements around the world.

The default EF Core 2.0 standard is to use DeleteBehavior.Restrict for DeleteBehavior.ClientSetNull and DeleteBehavior.ClientSetNull for additional relationships. As a workaround, I can suggest a typical metadata model loop at the end of the OnModelCreating override. In this case, find all relationships already discovered and modify them accordingly:

 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); } 
+9
source

Source: https://habr.com/ru/post/1272280/


All Articles