Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF7 RC1 : Disable Cascade Delete

Tags:

In the RC1 of EntityFramework 7, released yesterday, Cascade Delete was added.

To disable it per relationship, I can use :

      builder.Entity<Site>().HasOne(e => e.Person)       .WithMany(x => x.Sites).Metadata.DeleteBehavior = DeleteBehavior.Restrict; 

I want to disable it globally for a DbContext, but I didn't find a way. How can I do ?

like image 737
Adrien Constant Avatar asked Nov 19 '15 15:11

Adrien Constant


People also ask

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?

ON DELETE CASCADE : if a row of the referenced table is deleted, then all matching rows in the referencing table are deleted. ON DELETE SET NULL : if a row of the referenced table is deleted, then all referencing columns in all matching rows of the referencing table to be set to null.


1 Answers

Someone stated on the github project forum that the only way to do it right now is to iterate through all relationships in the method OnModelCreating(ModelBuilder builder), and set the DeleteBehavior property to DeleteBehavior.Restrict :

        foreach (var relationship in builder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))         {             relationship.DeleteBehavior = DeleteBehavior.Restrict;         } 
like image 168
Adrien Constant Avatar answered Sep 20 '22 23:09

Adrien Constant