I'm attempting to set Entity Framework to cascade on delete with an optional foreign key. I'm using code first, and my model looks like this:
public class Node
{
[Key]
public int ID { get; set; }
[ForeignKey("Parent")]
public int? ParentID { get; set; }
public virtual Node Parent { get; set; }
}
I've seen plenty of solutions that suggest, "Just make the foreign key required," but this will not work for me because the parent node may be null.
Does a solution exist that doesn't involve manually deleting child nodes before parent nodes?
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.
A foreign key with cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete in SQL Server.
Is this what you are looking for?
Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship
From the above, it would be something like (but I have not tried it):
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Node>()
.HasOptional(a => a.Parent)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
}
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