![](/img/trans.png)
[英]Adding an existing entity to a child collection of a many-to-many relationship
[英]Adding existing models to many-to-many relationship with Entity Framework 5
我有一個表,模塊和一個學生表,它們通過數據透視表ModuleStudents具有多對多關系。 我正在嘗試將學生添加到模塊中,但是遇到錯誤:
在TestingEF.exe中發生了類型為'System.NullReferenceException'的未處理異常
附加信息:對象引用未設置為對象的實例。
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; }
}
嘗試更改模塊類,在默認構造函數中創建“學生”列表,如下所示:
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; }
}
異常的調用堆棧會很好,但是如果我不得不做出一個瘋狂的猜測,我會說在此行module.Students.Add(student);
, Students
為null
module.Students.Add(student);
。 您是否首先使用代碼來構建模型? 如果是這樣,那么您可以在Module's
構造函數中初始化Students
; 像這樣:
public Module
{
Students = new List<Student>();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.