1

我创建了以下 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; }
}
4

3 回答 3

2

据我所知,这应该有效:

Answers = m.Answers.Select(a => 
              new AnswerDetail { AnswerId = a.AnswerId, 
                                 Text = a.Text }).ToList(),

您有一个列表Answer并将它们转换为AnswerDetail.

于 2013-09-15T14:08:57.773 回答
1

if you need a subset of q.Answers and you have a condition you can do:

QuestionDetail questions = _questionsRepository
            .GetAll()
            .Include(q => q.Answers)
            .Select(m => new QuestionDetail
            {
                QuestionId = m.QuestionId,
                Text = m.Text,
                Answers = m.Answers.Where(x=>yourCondition)
            })
            .FirstOrDefault();
于 2013-09-15T14:05:32.363 回答
1

尝试这个:

Take(1) 而不是“外部”上的 FirstOrDefault 项目结果:

QuestionDetail questions = _questionsRepository
        .GetAll()
        .Include(q => q.Answers)
        .Take(1)
        .ToList()
        .Select(m => new QuestionDetail
        {
            QuestionId = m.QuestionId,
            Text = m.Text,
            Answers = m.Answers.Select(a => 
                              new AnswerDetail { AnswerId = a.AnswerId, 
                                                 Text = a.Text }).ToList()
        });
于 2013-09-15T14:49:29.637 回答