Cascade delete in Entity Framework 6 fails to delete dependents. Any suggestions

c# entity-framework entity-framework-6

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 asscociated 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 asscociated coaches with a sport in Coach Table. Any suggestions on why the Coach name is not being deleted and how I can fix this ?

1
0
9/10/2019 10:52:04 PM

Popular Answer

You will have to use the fluent API to do this.

Try adding the following to your DbContext:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{   
    modelBuilder.Entity<User>()
        .HasOptional(a => a.UserDetail)
        .WithOptionalDependent()
        .WillCascadeOnDelete(true);
}
0
9/12/2019 5:36:25 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow