我使用代码优先在运行时生成数据库和数据。
我的两个班级/模特有一对多的关系。由于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();
}
答案 0 :(得分:2)
请勿手动添加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会处理这种关系。