I have a table, Modules and a table Students, that have a many-to-many relationship through a pivot table ModuleStudents. I am trying to add students to a module but encounter an error:
An unhandled exception of type 'System.NullReferenceException' occurred in TestingEF.exe
Additional information: Object reference not set to an instance of an object.
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();
What am I doing wrong here? I am fetching all the modules in the database and returning them as a list which I am then iterating over and trying to add a student to? I don't understand why I am receiving a System.NullReferenceException
Contents of the output from the excpetion: https://gist.github.com/anonymous/bb719a215ded5518af46
I am using Code First for this project (a learning exercise using a Console Solution).
Module class:
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; }
}
Student class:
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; }
}
Try changing your Module class creating the Students list in the default constructor, like this:
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; }
}
A call stack for the exception would be nice but if I had to make a wild guess, I would say that Students
is null
in this line module.Students.Add(student);
. Are you using code first to build your models? If so then you can initialize Students
in Module's
constructor; like so:
public Module
{
Students = new List<Student>();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.