【问题标题】:ASP.NET Core MVC List property of model empty in view模型的 ASP.NET Core MVC List 属性在视图中为空
【发布时间】:2018-08-12 08:54:53
【问题描述】:

假设我的 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();

在调试应用程序时,问题模型数据保存到数据库中,当然在 Web 应用程序中也是可见的。

考试似乎也是如此。但是,当我尝试在“考试”视图中获取问题时,“问题”字段似乎为空。 我用

@foreach(模型中的变量 i)

在视图中,调试时,此 foreach 中两个考试的 Question 字段计数均为 0 / 为空。

为了以防万一,我提供了一些调试和数据库数据查看器的屏幕截图; https://imgur.com/a/B9YbtHa


我已尽力找出问题所在,但没有成功。也许这个问题之前已经被问过很多次了,但是我用我搜索它的方式找不到它,如果这又是一个重复的话,很抱歉。

【问题讨论】:

  • ExamId 和 QuestionId 是数据库中的自动增量字段吗?
  • 是的,每个新条目都会自动递增
  • 你能在视图中显示代码吗?
  • 从数据库加载时需要包含数据:_context.Exams.Include(x =&gt; x.Questions)

标签: c# asp.net-core-mvc entity-framework-core


【解决方案1】:

是Eager Loading,你可以使用Include方法来指定要包含在查询结果中的相关数据。使用下面的代码。

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

【讨论】:

    猜你喜欢
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多