1

I've been struggling with this for a while but can't figure out what's happening. Im trying to establish a many-to-many relationship between two entities using EF, but it runs into the following error:

Introducing FOREIGN KEY constraint 'FK_CourseStudent_Students_StudentId' on table 'CourseStudent' 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 or index. See previous errors.

Here's my Course entity

public class Course
{
    public Course()
    {
        Students = new HashSet<Student>();
    }

    [Key]
    public int CourseId { get; set; }

    [Required]
    public string Name { get; set; }

    public int TeacherRefId { get; set; }

    [ForeignKey("TeacherRefId")]
    public virtual Teacher Teacher { get; set; }
    public virtual ICollection<Student> Students { get; set; }
}

And here's my Student entity

public class Student
{
    public Student()
    {
        Courses = new HashSet<Course>();
    }

    [Key]
    public int StudentId { get; set; }

    [Required]
    public string Name { get; set; }

    public int StandardRefId { get; set; }

    [ForeignKey("StandardRefId")]
    public virtual Standard Standard { get; set; }
    public virtual StudentAddress StudentAddress { get; set; }
    public virtual ICollection<Course> Courses { get; set; }
}

The other relationships seems to run properly, but this one keeps running into this error. What is the appropiate way to resolve this issue?

  • First you need to find the cycle. Doing so requires seeing related entities and their relationships. Note that EF Core (SqlServer) reports the first place where the cycle is detected. but not the relationships graph causing it. Once you find it, you have to break it somewhere (not necessarily for the entity being reported) by turning cascade delete off and handling the deletion of the related data manually or via trigger. – Ivan Stoev Feb 07 '23 at 06:46

0 Answers0