1

I have these codes that displays the first student record and first group record in my database in the Index page:

var studentToAdd = db.Students.FirstOrDefault();
var selectedGroup = db.Groups.FirstOrDefault();
ViewBag.Name = studentToAdd.Firstname;
ViewBag.Group = selectedGroup.GroupName;

It works and it displays "Richard" and "Group1" in my index page. But when I add this code that should add "Richard" to "Group1" I get a null object exception :

selectedGroup.Students.Add(studentToAdd);

How do i fix this? thanks

4

2 回答 2

3

当您尝试添加时,此时selectedGroup.Students属性为null.

做这个

if (selectedGroup.Students == null)
    selectedGroup.Students = new List<Student>(); // If its a List

selectedGroup.Students.Add(studentToAdd);
于 2013-06-09T11:27:47.767 回答
1

你的查询var selectedGroup = db.Groups.FirstOrDefault()返回一个属性为空的Group对象,我猜。Students您可以通过设置断点和调试代码来找到保存空引用的变量。

解决方案取决于您使用的技术以及您的Groups类的外观(其中包括延迟加载virtual属性)。该类的构造函数Groups还可以初始化一个空集合Students,然后您可以向其中添加实体.Add()

于 2013-06-09T11:28:06.080 回答