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>();
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.
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.
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.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With