Entity Framework Code-First(15):Cascade Delete

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.

转载于:https://www.cnblogs.com/purplefox2008/p/5644329.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值