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

我的两个类/模型具有一对多关系。由于FK不能为空,因此我在插入学生之前先插入标准,然后也手动输入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();
}

最佳答案

不要手动添加您的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将负责处理该关系。

10-02 04:48
查看更多