2

I'm using Entity Framework Core with Code First approach but receive following error when trying to start application:

System.Data.SqlClient.SqlException: 'Introducing FOREIGN KEY constraint 'FK_Grades_Students_StudentId' on table 'Grades' 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.'

My entities:

public class Student
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string Password { get; set; }

    public string Email { get; set; }

    public Group Group { get; set; }

    public IEnumerable<Subject> Subjects { get; set; } = new List<Subject>();


}

public class Subject
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

    public string Name { get; set; }

    public IEnumerable<Grade> Grades { get; set; } = new List<Grade>();

    [ForeignKey("StudentId")]

    public Student Student { get; set; }

    public Guid StudentId { get; set; }

}

public class Grade
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

    public double Value { get; set; }

    public DateTime DateOfGettingGrade { get; set; }

    [ForeignKey("SubjectId")]

    public Subject Subject { get; set; }

    public Guid SubjectId { get; set; }

    [ForeignKey("StudentId")]

    public Student Student { get; set; }

    public Guid StudentId { get; set; }
}


modelBuilder.Entity("GradeBook.Core.Models.Grade", b =>
            {
                b.HasOne("GradeBook.Core.Models.Student", "Student")
                    .WithMany()
                    .HasForeignKey("StudentId")
                    .OnDelete(DeleteBehavior.Cascade);

                b.HasOne("GradeBook.Core.Models.Subject", "Subject")
                    .WithMany("Grades")
                    .HasForeignKey("SubjectId")
                    .OnDelete(DeleteBehavior.Cascade);
            });
user8748535
  • 21
  • 1
  • 3

2 Answers2

2

You have an unnecessary foreign key on Grade. Grade references Subject and Subject references Student. So referencing Student from Grade when Subject also references Student creates a redundant path. Remove Student from either Grade or Subject.

Chris Stillwell
  • 10,266
  • 10
  • 67
  • 77
0

The reason for multiple cascade paths is that you can get from Grade to Subject in 2 ways - either Grade -> Student -> Subject or the direct connection Grade -> Subject. You have to remove one of the references, and my suggestion is to go for removing the connection between Student and Subject tables. Use the Grades table as the Many-To-Many relations table.

m3n7alsnak3
  • 3,026
  • 1
  • 15
  • 24