6

我有以下课程:

public class Problem : AuditableTable
{
    public Problem()
    {
        this.Questions = new List<Question>();
    }
    public int ProblemId { get; set; }
    public string Title { get; set; }
    public virtual ICollection<Question> Questions { get; set; }
}

public Question()
    {
        this.Answers = new List<Answer>();
    }
    public int QuestionId { get; set; }
    public int ProblemId { get; set; }
    public virtual ICollection<Answer> Answers { get; set; }
    public virtual Problem Problem { get; set; }
}
public class Answer : AuditableTable
{
    public int AnswerId { get; set; }
    public int QuestionId { get; set; }
    public string Text { get; set; }
    public virtual Question Question { get; set; }
}

我想发出这样的查询:

        var problems = _problemsRepository.GetAll()
            .Where(p => p.ProblemId == problemId)
            .Include(p => p.Questions)
            .Include(p => p.Questions.Answers)
            .ToList();
        return problems;

所以我可以看到问题、问题和答案信息。但是我的最后一个包含有问题,我无法弄清楚如何包含答案。

有人可以给我一些建议吗?

4

2 回答 2

8

这在 EntityFramework 7.0 中有所改变。

新语法将采用以下形式

var problems = _problemsRepository.GetAll()
            .Where(p => p.ProblemId == problemId)
            .Include(p => p.Questions)
            .ThenInclude(q => q.Answers)
            .ToList();
于 2016-05-19T14:31:58.870 回答
5

您可以使用 .Select()。

var problems = _problemsRepository.GetAll()
            .Where(p => p.ProblemId == problemId)
            .Include(p => p.Questions.Select(q => q.Answers))
            .ToList();

现在您的答案将被包括在内。

于 2013-08-17T07:49:38.927 回答