EF enables cascading delete effect by default for all the entities.
The following is copied from here.
Consider the following Student and Standard entities that have one-to-many relationship.
public class Student
{
public Student() { }
public int StudentId { get; set; }
public string StudentName { get; set; }
public virtual Standard Standard { get; set; }
}
public class Standard
{
public Standard()
{
Students = new List<Student>();
}
public int StandardId { get; set; }
public string Description { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
The following example demonstrates cascade delete effect between entities that have one-to-many relationship.
using( var ctx = new SchoolContext() ) {
var student1 = new Student() { StudentName = "James" };
var student2 = new Student() { StudentName = "Gandhi" };
var standard1 = new Standard() { StandardName = "Standard 1" };
student1.Standard = standard1;
student2.Standard = standard1;
ctx.Students.Add( student1 );
ctx.Students.Add( student2 );
//inserts students and standard1 into db
ctx.SaveChanges();
//deletes standard1 from db and also set standard_StandardId FK column in Students table to null for
// all the students that reference standard1.
ctx.Standards.Remove( standard1 );
ctx.SaveChanges();
}
In the above example, it deletes standard1 from db and also set standard_StandardId FK column in Students table to null for all the records that reference standard1.
EF automatically deletes related records in the middle table for many-to-many relationship entities if one or other entity is deleted.
Thus, EF enables cascading delete effect by default for all the entities.