Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable cascade delete on EF Core 2 globally

I need to know about ways of disabling cascade delete in EF Core 2 globally. Any help is appricated.

In EF 6.x we used following code to disable cascade delete on both OneToMany and ManyToMany realtions:

builder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); builder.Conventions.Remove<ManyToManyCascadeDeleteConvention>(); 
like image 213
Afshar Mohebi Avatar asked Oct 02 '17 13:10

Afshar Mohebi


People also ask

How do I turn off cascade delete?

Using Fluent API, you can configure entities to turn off cascade delete by calling the WillCascadeOnDelete(false) method. Now when the author entity is deleted, the related books won't be deleted from the database.

Is Cascade delete default?

Cascade delete automatically deletes dependent records or sets null to ForeignKey columns when the parent record is deleted in the database. Cascade delete is enabled by default in Entity Framework for all types of relationships such as one-to-one, one-to-many and many-to-many.

What is Cascade delete in EF core?

Cascade delete allows the deletion of a row to trigger the deletion of related rows automatically. EF Core covers a closely related concept and implements several different delete behaviors and allows for the configuration of the delete behaviors of individual relationships.

What is on delete cascade and on Delete Set default?

It means that the child data is set to NULL when the parent data is deleted or updated. SET DEFAULT. It is used in conjunction with ON DELETE or ON UPDATE. It means that the child data is set to their default values when the parent data is deleted or updated.


1 Answers

Unfortunately EF Core currently (latest at this time v2.0) does not expose a good way to control the conventions globally.

The default EF Core 2.0 convention is to use DeleteBehavior.Cascade for required and DeleteBehavior.ClientSetNull for optional relationships. What I can suggest as workaround is a typical metadata model loop at the end of the OnModelCreating override. In this case, locating all the already discovered relationships and modifying 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); } 
like image 61
Ivan Stoev Avatar answered Oct 11 '22 22:10

Ivan Stoev