簡體   English   中英

模型的ASP.NET Core MVC List屬性在視圖中為空

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

假設我的MVC應用程序中有兩個模型:

考試

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

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

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

public string TheQuestionItself { get; set; }

我用它來將一些預定義的數據播種到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();

在調試應用程序時,Question模型數據將保存到數據庫中,並且當然在Web應用程序中也是可見的。

考試似乎也是如此。 但是,當我嘗試在“考試”視圖中獲取問題時,“問題”字段似乎為空。 我用

@foreach(模型中的var i)

在視圖中,以及在調試時,此foreach中兩個考試的“問題”字段的計數均為0 /為空。

我提供了一些調試和數據庫數據查看器的屏幕截圖,以防萬一; https://imgur.com/a/B9YbtHa


我已盡力找到問題所在,但沒有成功。 也許以前曾多次問過這個問題,但我用搜索的方式找不到它,所以如果這又是重復的話,抱歉。

這是急切的加載,您可以使用Include方法指定要包含在查詢結果中的相關數據。 使用下面的代碼。

_context.Exams.Include(x => x.Questions);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM