将现有模型添加到与Entity Framework 5的多对多关系

时间:2014-05-11 18:20:38

标签: c# asp.net-mvc linq entity-framework

我有一个表,模块和表格学生,通过数据透视表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; }
}

2 个答案:

答案 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)

异常的调用堆栈会很好但是如果我不得不做出一个疯狂的猜测,我会说Studentsnull行中module.Students.Add(student);。您是否首先使用代码来构建模型?如果是,那么您可以在Students构造函数中初始化Module's;像这样:

public Module
{
    Students = new List<Student>();
}