在Entity Framework的帮助下检索数据时,我想填充子ViewModel,它恰好是一个集合。下面的查询工作正常,但只使用子模型(集合)的第一项填充内部ViewModel。如何使用所有相应的模型数据填充内部ViewModel。
var pagedQuestions = _ctx.VoteQuestions.Include(q => q.VoteAnswerOptions).Select(q => new Question
{
QuestionStr = q.Name,
QuestionId = q.Id,
IsMultipleAnswerQuestion = q.VoteType.Id == 1 ? false : true,
PossibleAnswers = new List<PossibleAnswer>
{
new PossibleAnswer
{
AnswerId = q.VoteAnswerOptions.FirstOrDefault().Id,
AnswerStr = q.VoteAnswerOptions.FirstOrDefault().Answer
}
}
});
答案 0 :(得分:0)
您可以在第一个Select
内完成第二个Select
:
var pagedQuestions = _ctx.VoteQuestions.Select(q => new Question
{
QuestionStr = q.Name,
QuestionId = q.Id,
IsMultipleAnswerQuestion = q.VoteType.Id == 1 ? false : true,
PossibleAnswers = q.VoteAnswerOptions
.Select(a => new PossibleAnswer
{
AnswerId = a.Id,
AnswerStr = a.Answer
}
)
}
});
您不需要Include
。实体框架将加入VoteAnswerOptions
本身,并从中选择所需的字段。