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

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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().

4 Comments

You can find the variable that holds the null reference by ... debugging your code OP debugging their code? What a novel idea..
@ta.speot.is I agree, it's much easier to put the code online and let others do that for you.
Thanks. But believe it or not I tried my best debugging my code before I posted this question. Maybe I'm just not debugging the right way.
@WannaCSharp how did you resolve it? And no problem, I gave you a hint how to debug this the next time. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.