以FK关系向数据库插入数据

本文关键字:插入 数据 数据库 FK 关系 | 更新日期: 2023-09-27 18:12:16

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

我的两个类/模型有一对多关系。由于FK不能为空,我首先插入Standard,然后再插入Student,并且我也手动键入FK ID。但我仍然得到System.NullReferenceException,我只是不明白为什么?

我试着谷歌,但我找不到相关的文章插入数据与外部关系从头开始在代码优先。

我的实体类/模型

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();
}

以FK关系向数据库插入数据

不要手动添加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会处理这个关系