简体   繁体   English

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

[英]How can I .Include down more than one level in LINQ?

I have the following classes: 我有以下课程:

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; }
}

I want to issue a query like this: 我想发出这样的查询:

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

So I can see Problem, Question and Answer information. 所以我可以看到问题,问题和答案信息。 But there is a problem with my last include and I cannot work out how to get the Answers included. 但我的最后一个包含有一个问题,我无法弄清楚如何包含答案。

Can someone give me some advice on this. 有人可以给我一些建议。

This is changed in EntityFramework 7.0. 这在EntityFramework 7.0中已更改。

The new syntax would take the form 新语法将采用该形式

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

You can use .Select(). 您可以使用.Select()。

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

Now your answers will be included. 现在你的答案将被包括在内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM