如何创建一个连接四个表的LINQ表达式并允许最顶层表的位置?

时间:2013-09-02 14:31:10

标签: c# linq

我有以下课程:

public partial class Topic
{
    public Topic()
    {
        this.SubTopics = new List<SubTopic>();
    }
    public int TopicId { get; set; }
    public string Name { get; set; }
    public int SubjectId { get; set; }
    public virtual Subject Subject { get; set; }
    public virtual ICollection<SubTopic> SubTopics { get; set; }
}
public partial class SubTopic
{    
    public SubTopic()
    {
        this.Problems = new List<Problem>();
    }
    public int SubTopicId { get; set; }
    public int TopicId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Problem> Problems { get; set; }
    public virtual Topic Topic { get; set; }

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

有人可以帮我告诉我如何构建LINQ表达式。我需要做的只是获得具有SubjectId = 0的问题的QuestionId。

这是我创建的LINQ,用于解答ProblemId的问题:

var questions = _questionsRepository
        .GetAll()
        .Where(a => a.ProblemId == problemId)
        .ToList();

为此,有人可以告诉我如何让LINQ表达式连接所有上面的表,这样我就可以输入一个SubjectId = 0;

1 个答案:

答案 0 :(得分:3)

您拥有所需的所有导航属性,因此您可以这样做:

var questions = _questionsRepository.GetAll()
.Where(m => m.Problem.SubTopic.Topic.SubjectId == 0)
.Select(m => m.QuestionId);

你可能需要一些空检查

.Where(m => m.Problem != null && 
            m.Problem.SubTopic ! null && 
            m.Problem.SubTopic.Topic != null &&
            m.Problem.SubTopic.Topic.SubjectId == 0)
.Select(m => m.QuestionId);