WannaCSharp
WannaCSharp

Reputation: 1898

Null Object Reference Exception

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

Upvotes: 1

Views: 380

Answers (2)

CodeCaster
CodeCaster

Reputation: 151720

Your query var selectedGroup = db.Groups.FirstOrDefault() returns a Group object whose Students property is null, I guess. You can find the variable that holds the null reference by setting a breakpoint and debugging your code.

The solution depends on what techniques you use and what your Groups class looks like (amongst others lazy loading on virtual properties). The constructor of the Groups class can also initialize an empty Students collection, to which you can then add entities with .Add().

Upvotes: 1

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48590

When you try to add, at that point selectedGroup.Students property is null.

Do this

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

selectedGroup.Students.Add(studentToAdd);

Upvotes: 3

Related Questions