• 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.

  • 相关阅读:
    redis分布式锁解决超卖问题
    redis使用
    Xcode 解决日志打印不全问题
    苹果电脑系统怎么重装?这几步就可以轻松搞定
    Mac 一键显示所有隐藏文件 不要那么六好吧
    iOS导入高德地图出现缺失armv7--"Undefined symbols for architecture armv7"
    如何生成.a文件,小心有坑!!
    保护你的代码,生成.a文件以及.framework文件需要注意的地方
    二维码扫描工具实现
    iOS 调整图片尺寸,告诉你的UI,别问我尺寸!我要最大的
  • 原文地址:https://www.cnblogs.com/purplefox2008/p/5644329.html
Copyright © 2020-2023  润新知