我创建了以下 LINQ 代码:
QuestionDetail questions = _questionsRepository
.GetAll()
.Include(q => q.Answers)
.Select(m => new QuestionDetail
{
QuestionId = m.QuestionId,
Text = m.Text,
Answers // << I am not sure how to populate this
// << I need to have a new collection
// << created from a subset of the m.Answers
})
.FirstOrDefault();
我的问题是我不确定如何填充ICollection<AnswerDetail> Answers
属于 QuestionDetail 的集合。我需要以某种方式从 m.Answers 中选择并使用它来填充 AnswerDetail 集合。我知道我不能使用新的 AnswerDetail,因为 Answers 是一个集合。
任何人都可以帮助并告诉我如何做到这一点。
下面我列出了一些用于此的类。为了更简单,我从问题和答案类中删除了一些字段。
public class QuestionDetail
{
public int QuestionId { get; set; }
public string Text { get; set; }
public virtual ICollection<AnswerDetail> Answers { get; set; }
}
public class AnswerDetail
{
public int AnswerId { get; set; }
public string Text { get; set; }
}
public class Answer
{
public int AnswerId { get; set; }
public int QuestionId { get; set; }
public Nullable<bool> Correct { get; set; }
public Nullable<bool> Response { get; set; }
public string Text { get; set; }
public virtual Question Question { get; set; }
}
public class Question
{
public Question()
{
this.Answers = new List<Answer>();
}
public int QuestionId { get; set; }
public string Text { get; set; }
public string Image { get; set; }
public virtual ICollection<Answer> Answers { get; set; }
}