我正在使用带有Code First方法的Entity Framework Core但在尝试启动应用程序时收到以下错误:
System.Data.SqlClient.SqlException:'介绍FOREIGN KEY 约束' FK_Grades_Students_StudentId'在桌上'成绩'可能会导致 循环或多个级联路径。指定ON DELETE NO ACTION或ON 更新无操作,或修改其他FOREIGN KEY约束。不能 创建约束或索引。查看以前的错误。'
我的实体:
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);
});
答案 0 :(得分:1)
Grade
上有一个不必要的外键。 Grade
引用Subject
和Subject
引用Student
。因此,Student
引用Grade
时引用Subject
Student
会引发冗余路径。从Student
或Grade
移除Subject
。
答案 1 :(得分:0)
多个级联路径的原因是您可以通过两种方式从Grade
到Subject
- Grade -> Student -> Subject
或直接连接Grade -> Subject
。您必须删除其中一个引用,我的建议是删除Student
和Subject
表之间的连接。使用Grades
表作为“多对多关系”表。