简体   繁体   中英

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

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM