我有一个表,模块和表格学生,通过数据透视表ModuleStudents具有多对多关系。我正在尝试将学生添加到模块但遇到错误:
类型'System.NullReferenceException'的未处理异常 发生在TestingEF.exe
中附加信息:对象引用未设置为的实例 对象
SchoolContext context = new SchoolContext();
List<Module> modules = context.Modules.ToList();
Student student = context.Students.Single(s => s.MatriculationNumber == 40122047);
foreach (Module module in modules)
{
module.Students.Add(student);
}
context.SaveChanges();
我在这里做错了什么?我正在获取数据库中的所有模块并将它们作为列表返回,然后我将迭代并尝试添加学生?我不明白为什么我收到System.NullReferenceException
摘要输出的内容:https://gist.github.com/anonymous/bb719a215ded5518af46
我正在使用Code First进行此项目(使用控制台解决方案进行学习练习)。
模块类:
class Module
{
public int ModuleID { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public virtual Course Course { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
学生班:
class Student
{
public int StudentID { get; set; }
public int MatriculationNumber { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public virtual Course Course { get; set; }
public virtual ICollection<Module> Modules { get; set; }
}
答案 0 :(得分:2)
尝试更改Module类,在默认构造函数中创建Students列表,如下所示:
class Module
{
public Module()
{
this.Students = new List<Student>();
}
public int ModuleID { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public virtual Course Course { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
答案 1 :(得分:1)
异常的调用堆栈会很好但是如果我不得不做出一个疯狂的猜测,我会说Students
在null
行中module.Students.Add(student);
。您是否首先使用代码来构建模型?如果是,那么您可以在Students
构造函数中初始化Module's
;像这样:
public Module
{
Students = new List<Student>();
}