0

我有以下课程:

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;

4

1 回答 1

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);
于 2013-09-02T14:35:39.640 回答