我怎么能.在LINQ中包含多个级别?

6 c# linq

我有以下课程:

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; }
}
Run Code Online (Sandbox Code Playgroud)

我想发出这样的查询:

        var problems = _problemsRepository.GetAll()
            .Where(p => p.ProblemId == problemId)
            .Include(p => p.Questions)
            .Include(p => p.Questions.Answers)
            .ToList();
        return problems;
Run Code Online (Sandbox Code Playgroud)

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

有人可以给我一些建议.

Ham*_*hid 7

这在EntityFramework 7.0中已更改.

新语法将采用该形式

var problems = _problemsRepository.GetAll()
            .Where(p => p.ProblemId == problemId)
            .Include(p => p.Questions)
            .ThenInclude(q => q.Answers)
            .ToList();
Run Code Online (Sandbox Code Playgroud)


Jon*_*s W 5

您可以使用.Select().

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

现在你的答案将被包括在内.

  • 第一个"包括"已经过时了.第二个还将包括问题. (2认同)