Entity Framework Code-First(15):Cascade Delete

追憶似水流年發表於2016-07-05

Cascade Delete in Entity Framework Code-First:

Cascade delete automatically deletes dependent records or set null to foreignkey properties when the principal record is deleted.

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.

Cascade delete in one-to-one relationship:

Consider the following Student and StudentAddress entities that have one-to-zero-or-one relationship.

public class Student
{
    public Student() { }

    public int StudentId { get; set; }
    public string StudentName { get; set; }

    public virtual StudentAddress Address { get; set; }

}
     
public class StudentAddress 
{
    [ForeignKey('Student')]
    public int StudentAddressId { get; set; }
        
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public int Zipcode { get; set; }
    public string State { get; set; }
    public string Country { get; set; }

    public virtual Student Student { get; set; }
}

 

The following example demonstrates cascade delete operation when Student is removed.

using (var ctx = new SchoolContext()) {

    var student1 = new Student() { StudentName = "James" };
    var address1 = new StudentAddress() { Address1 = "address" };

    student1.Address = address1;

    ctx.Students.Add(student1);

    ctx.SaveChanges();
    // student1 and its address will be removed from db
    ctx.Students.Remove(student1);

    ctx.SaveChanges();
}

 

In the above example, first it saves student and studentAddress into database and then when it removes student1 and call SaveChanges(), EF will delete student1 as well as its StudentAddress from the database. Thus, EF enables cascade delete by default.

Cascade Delete in One-to-Many Relationship:

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.

Turn off cascading delete:

Use Fluent API to configure entities to turn off the cascading delete as shown below.

public class SchoolContext<: DbContext
{
    public SchoolContext():base("MySchool")
    {
                }

    public DbSet<Student> Students { get; set; }
    public DbSet<Standard> Standards { get; set; }
        
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Student>()
            .HasOptional<Standard>(s => s.Standard)
            .WithMany()
            .WillCascadeOnDelete(false);
    }
}

 

Note: DataAnnotations does not include any attribute to turn off cascading delete.

相關文章