I would like to enable CASCADE DELETE on a table using code-first. When the model is re-created from scratch, there is no CASCADE DELETE set even though the relationships are set-up automatically. The strange thing is that it DOES enable this for some tables with a many to many relationship though, which you would think it might have problems with.
Setup: Table A <- Table B.
Table B's FK points to Table A's PK.
Why would this not work?
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.
Hosted by host. Relationship classes with a cardinality of one-to-one or one-to-many have an option called cascading delete. This option causes a destination member of the relationship and all relationships below it to be deleted when the source member is deleted.
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.
Possible reason why you don't get cascading delete is that your relationship is optional. Example:
public class Category { public int CategoryId { get; set; } } public class Product { public int ProductId { get; set; } public Category Category { get; set; } }
In this model you would get a Product table which has a foreign key to the Category table but this key is nullable and there is no cascading delete setup in the database by default.
If you want to have the relationship required then you have two options:
Annotations:
public class Product { public int ProductId { get; set; } [Required] public Category Category { get; set; } }
Fluent API:
modelBuilder.Entity<Product>() .HasRequired(p => p.Category) .WithMany();
In both cases cascading delete will be configured automatically.
If you want to have the relationship optional but WITH cascading delete you need to configure this explicitely:
modelBuilder.Entity<Product>() .HasOptional(p => p.Category) .WithMany() .WillCascadeOnDelete(true);
Edit: In the last code snippet you can also simply write .WillCascadeOnDelete()
. This parameterless overload defaults to true
for setting up cascading delete.
See more on this in the documentation
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