原文連接:https://www.entityframeworktutorial.net/code-first/cascade-delete-in-code-first.aspxhtml
EF 6 Code-First系列文章目錄:數據庫
當數據庫的父記錄被刪除的時候,級聯刪除自動的刪除相關的依賴記錄,或者設置外鍵列爲NULL。app
EF 對於一對一,一對多,多對多關係,默認是啓用了級聯刪除。ide
下面的Student和StudentAddress實體,是一對零或一的關係。測試
public class 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; } }
下面的操做,演示了級聯刪除。ui
using (var ctx = new SchoolContext()) { var stud = new Student() { StudentName = "James" }; var add = new StudentAddress() { Address1 = "address" }; stud.Address = add; ctx.Students.Add(stud); ctx.SaveChanges(); ctx.Students.Remove(stud);// student and its address will be removed from db
ctx.SaveChanges(); }
在上面的代碼中,首先,EF保存stud和其StudentAddress實體到數據庫中,而後刪除stud,調用SaveChanges().EF就會刪除stud,而且將StudentAddress表中相關級聯一併刪除。因此,EF默認是級聯刪除的。spa
一對多關係中的級聯刪除.net
下面的Student和Standard實體,是一對多關係。翻譯
public class 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; } }
下面的代碼,演示了一對多關係中的級聯刪除。code
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(); }
在上面的例子中,EF從數據庫中刪除了standard1,而且設置Students表中的相關聯的standard_StandardId外鍵列爲null。
請注意:對於多對多關係,若是兩個實體中的任何一個刪除了,EF自動的刪除中間表中相關的記錄。
因此,EF默認是對全部的實體【一對一的中的實體、一對多中的實體、多對多中的實體】啓用了級聯刪除。
關閉級聯刪除
能夠用Fluent API中的WillCascadeOnDelete()來處理級聯刪除,例如:
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); } }
請注意:沒有數據註解的特性,能夠用來關閉級聯刪除。