向具有 FK 关系的数据库中插入数据

Insert data to database with FK relation

我使用代码优先在运行时生成数据库和数据。

我的两个classes/models是一对多的关系。由于 FK 不能为空,因此我先插入 Standard,然后再插入 Student,并且我还手动输入 FK ID。但我仍然得到 System.NullReferenceException,我只是不明白为什么?

我试过谷歌搜索,但我找不到关于在代码优先中从头开始插入具有外部关系的数据的相关文章。

我的实体Class/Model

public class Student {
    public Student() { }
    public int StudentID { get; set; }
    public string StudentName { get; set; }

    public int StandardId { get; set; } // FK StandardId
    public Standard Standard { get; set; } }

public class Standard {
    public Standard() { }
    public int StandardId { get; set; }
    public string StandardName { get; set; } 

    public ICollection<Student> Students { get; set; } }

我的主要

using (MyDbContext ctx = new MyDbContext())
{
    Standard std = new Standard();
    ctx.Standards.Add(std);
    ctx.SaveChanges(); // Database already has a StandardID = 1

    Student stud = new Student()
    {
        StudentName = "John",
        StandardId = 1  // I even manually type in the FK
    };

    ctx.Student.Add(stud); // I still get 'System.NullReferenceException'
    ctx.SaveChanges();
}

不要手动添加您的 StandardId,请这样做:

using (MyDbContext ctx = new MyDbContext())
{
    Standard std = new Standard();

    Student stud = new Student()
    {
        StudentName = "John",
    };

    stud.Standard = std;

    ctx.Student.Add(stud);
    ctx.SaveChanges();
}

EF 会处理关系。