I have a table of questions and a table of answers
I always need to display the list of questions regardless and there is a corresponsing asnwer, I need to grab that answer (response)
I use the following code
var Questions = db.Questions.Where(x => x.isActive);
var Answers = db.Answers.Where(x => x.AssessmentID == 99);
AssessmentResponseVM model = new AssessmentResponseVM();
foreach (var question in Questions)
{
AnswerAndQuestions q = new AnswerAndQuestions { };
q.QuestionText = question.QuestionText;
q.QuestionID = question.ID;
q.Response = Answers.Where(a => a.QuestionID == question.ID).SingleOrDefault().Response; <--- throws exception if there is no answer for the question
model.Questions.Add(q);
}
But get this error
Object reference not set to an instance of an object.
On this line
q.Response = Answers.Where(a => a.QuestionID == question.ID).SingleOrDefault().Response;