none
Cascade delete in Entity Framework 6 fails to delete dependents. RRS feed

  • Question

  • I am new to Eternity Framework 6 and I read that by default Cascade Delete is enabled. I currently have the following models

    public class Student
    {
        public int Id { get; set; }
    
        public List<Sport> Sports { get; set; }
    
        public string StudentName { get; set; }
    }
    
    public class Sport
    {
        public int Id { get; set; }
    
        public string SportName { get; set; }
    
        public List<Coach> {get; set;} 
    }
    
    public class Coach
    {
        public int Id { get; set; }
    
        public string CoachName { get; set; }
    }

    This is what my context looks like

    public class MyContext: DbContext
    {
            public MyContext(): base("name=MContext")
            {
            }
            public DbSet<Student> Students{ get; set; }
    }

    Now this is how I am removing Sports played by a student. If cascade delete is turned on then all the coaches who are associated with a Sport should also be deleted but they are not being deleted.

    This is how I am removing items //Currently there is only 1 student in the DB 

    Student st = context.Students.SingleOrDefault();

    // Get all the Sports of this student this.context.Entry(st).Collection(x => x.Sports).Load(); // Clear the actions dm.Sports.Clear();

    The above basically assigns the Foreign Key of Student in Sports Table to NULL and it does not delete any of the associated coaches with a sport in Coach Table. Any suggestions on why the Coach name is not being deleted and how I can fix this ?


    A candle loses nothing by lighting another candle.

    Tuesday, September 10, 2019 10:59 PM

All replies

  • Hi,

    Did you try the method "WillCascadeOnDelete()"? Here I found a thread may help you.

    https://stackoverflow.com/a/17487948/8335151

    Regards,

    Kyle


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, September 11, 2019 5:20 AM
    Moderator
  • You can set it up at the DB engine level and just the the parent record that deleted records out of child tables when the party tevofy is deleted

    Wednesday, September 11, 2019 3:17 PM