如何在LINQ中包含多个级别
本文关键字:包含多 LINQ | 更新日期: 2023-09-27 18:28:11
我有以下类:
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;
这样我就可以看到问题、问答信息。但我上一次收录有问题,我不知道如何把答案收录进去。
有人能给我一些建议吗。
EntityFramework 7.0对此进行了更改。
新语法将采用的形式
var problems = _problemsRepository.GetAll()
.Where(p => p.ProblemId == problemId)
.Include(p => p.Questions)
.ThenInclude(q => q.Answers)
.ToList();
您可以使用.Select().
var problems = _problemsRepository.GetAll()
.Where(p => p.ProblemId == problemId)
.Include(p => p.Questions.Select(q => q.Answers))
.ToList();
现在你的答案将包括在内。