ASP.NET Core MVC List property of model empty in view

asp.net-core-mvc c# entity-framework-core

Question

Suppose I have two models in my MVC application:

Exam

[Key]
public int ExamId { get; set; }

public ExamModel() => Questions = new List<QuestionModel>();
public List<QuestionModel> Questions { get; set; }

Question

[Key]
public int QuestionId { get; set; }

public string TheQuestionItself { get; set; }

I use this to seed some predefined data into the database in DbInitializer

var questions = new Question[]
{
new Question{TheQuestionItself="Question 1"},
new Question{TheQuestionItself="Question 2"},
new Question{TheQuestionItself="Question 3"},
new Question{TheQuestionItself="Question 4"},
new Question{TheQuestionItself="Question 5"},
};
foreach (var i in questions)
{ context.Questions.Add(i); }
context.SaveChanges();


var exam = new Exam[]
{
    new Exam{
        Questions = new List<Question> {
            context.Questions.Find(1),
            context.Questions.Find(2),
            context.Questions.Find(3),
            }
    },
    new Exam{
        Questions = new List<Question>{
            context.Questions.Find(4),
            context.Questions.Find(5),
        }
    },
};
foreach (var i in exam)
{
    context.Exams.Add(i);
}
context.SaveChanges();

While debugging the application the Question model data saves to the database and of course is visible in the web application as well.

The same appears to be the case for the Exam. However, when I try to fetch the questions in the Exam view, the Question field appears to be empty. I use

@foreach (var i in Model)

in the view, and while debugging, the Question field of both of the Exams in this foreach has a count of 0 / are empty.

I inlucded some screenshots of the debugging and database data viewer just in case; https://imgur.com/a/B9YbtHa


I have tried my best to find what the problem for this seems to be, but to no success. Perhaps this problem has been asked multiple times before but I couldn't find it with the way I've searched for it, so sorry if this is yet another duplicate.

1
1
8/11/2018 1:11:18 PM

Accepted Answer

It’s Eager Loading, You can use the Include method to specify related data to be included in query result. Use the below code.

_context.Exams.Include(x => x.Questions);
0
8/12/2018 12:54:53 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow