实体框架Core 2.0 SqlException:INSERT语句与FOREIGN KEY约束冲突

时间:2018-03-03 12:13:29

标签: c# entity-framework entity-framework-core

尝试播种数据库时出现异常:

  

SqlException:INSERT语句与FOREIGN KEY约束“FK_Grades_Students_StudentId”冲突。冲突发生在数据库“GradeBookDB”,表“dbo.Students”,列'Id'。

我的代码:

if (context.Students.Any())
{
    return;
}

var students = new List<Student>()
        {
            new Student()
            {
                FirstName = "John",
                LastName = "Smith"

                Subjects = new List<Subject>()
                {
                    new Subject()
                    {
                        Name = "Math",

                        Grades = new List<Grade>()
                        {
                            new Grade()
                            {
                                Value = 4
                            }
                        }
                    },
                }
            },
        };

context.Students.AddRange(students);
context.SaveChanges();

我从这些模型创建了迁移:

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

    public string FirstName { get; set; }
    public string LastName { 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>();
}

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

    public double Value { get; set; }

    [ForeignKey("SubjectId")]
    public Subject Subject { get; set; }

    public Guid SubjectId { get; set; }

    [ForeignKey("StudentId")]
    public Guid StudentId { get; set; }

    public Student Student { get; set; }
}

我做错了什么?我不知道为什么我会收到异常,因为当我从StudentId类中删除FK(Grade)并将FK(StudentId)添加到Subject类时,一切工作正常,没有例外。

0 个答案:

没有答案