EF Code-First 學習之旅 級聯刪除

級聯刪除是當刪除主記錄的時候會自動刪除依賴的記錄或者設置外鍵屬性爲nullide

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; }
}

 

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();
}

 

級聯刪除:當刪除Student的時候也刪除StudentAddress測試

級聯刪除注意的:ui

  1.須要保證DbContext中已經加載了該父對象的全部子對象spa

    所以在查詢父對象的時候應該使用Include("子對象屬性名")查詢,code

    或者在DbContext另外把其下的全部子對象查詢出來對象

    再進行對父對象的刪除方可實現級聯刪除子對象blog

但注意以上所述狀況只適用於關聯子項比較少的狀況,數據量少的演示測試Demo能夠,工做中應該杜絕該類解決方案的出現。ip

 

一對多級聯刪除rem

 

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; }
}
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();
}

 

關閉級聯刪除get

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);
    }
}
相關文章
相關標籤/搜索