Although there are multiple solutions for such problems, but they are not allowing multiple cascade path but just disabling on delete cascade option from one reference.
But I want to allow on delete cascade from both references
For example in following case, Performance table information should be deleted whether Student is deleted or Course is deleted
public class Course
{
public int Id { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public string Department { get; set; }
public int TeacherId { get; set; }
public virtual Teacher Teacher { get; set; }
public virtual ICollection<Performance> Performances { get; set; }
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int StudentDetailId { get; set; }
public virtual StudentDetail StudentDetailId { get; set; }
public virtual ICollection<Performance> Performances { get; set; }
}
public class Performance
{
public int Id { get; set; }
public string Grade { get; set; }
public int Attendance { get; set; }
public int Activity { get; set; }
[Required]
public int StudentId { get; set; }
[ForeignKey("StudentId")]
public virtual Student Student { get; set; }
[Required]
public int CourseId { get; set; }
[ForeignKey("CourseId")]
public virtual Course Course { get; set; }
}
I also tried to modify database manually by adding ON DELETE CASCADE ON UPDATE CASCADE in both foreign keys, but SQL server does not allow me to do this as well. With above code I get following message:
Introducing FOREIGN KEY constraint 'FK_dbo.Performance_dbo.Course_CourseId' on table 'Performance' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint.
Problem goes away if I keep one cascade delete and other reference optional:
public class Performance
{
public int Id { get; set; }
public string Grade { get; set; }
public int Attendance { get; set; }
public int Activity { get; set; }
[Required]
public int StudentId { get; set; }
[ForeignKey("StudentId")]
public virtual Student Student { get; set; }
// [Required]
public int? CourseId { get; set; }
[ForeignKey("CourseId")]
public virtual Course Course { get; set; }
}
Please suggest a way of cascade delete from both references.