Cascade delete allows the deletion of a row to trigger the deletion of related rows automatically.
OnDelete
Fluent API method is used to specify the delete behavior for a dependent entity when the principal is deleted.The OnDelete
method takes a DeleteBehavior
enum as a parameter.
NULL
.Setting a foreign key value to null is not valid if the foreign key is not nullable. The following example set a foreign key field to null when the principal is deleted.
using (var context = new EntityContext())
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Book>()
.HasOne(b => b.Author)
.WithMany(a => a.Books)
.OnDelete(DeleteBehavior.SetNull);
}
}
The following example configures the relationship as required and specifies that dependant rows are deleted when the principal is deleted.
using (var context = new EntityContext())
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Book>()
.HasOne(b => b.Author)
.WithMany(a => a.Books)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
}
}
There are four delete behaviors.
It is possible to save a null foreign key value, which results in the following effects.
Behavior Name | Effect on dependent/child in memory | Effect on dependent/child in database |
---|---|---|
Cascade | Entities are deleted | Entities are deleted |
ClientSetNull (Default) | Foreign key properties are set to null | None |
SetNull | Foreign key properties are set to null | Foreign key properties are set to null |
Restrict | None | None |
It is not possible to save a null foreign key value, which results in the following effects.
Behavior Name | Effect on dependent/child in memory | Effect on dependent/child in database |
---|---|---|
Cascade (Default) | Entities are deleted | Entities are deleted |
ClientSetNull | SaveChanges throws | None |
SetNull | SaveChanges throws | SaveChanges throws |
Restrict | None | None |
Cascade
option is used when you have entities that cannot exist without a parent, and you want EF to take care of deleting the children automatically.ClientSetNull
is used when you have entities that may or may not have a parent, and you want EF to take care of nulling out the foreign key for you.SetNull
option is used when you want the database to also try to propagate null
values to child foreign keys even when the child entity is not loaded.SetNull
is not the default.Restrict
option is used when you don't want EF Core to ever delete an entity automatically or null out the foreign key automatically.