3

我正在使用 Entity Framework 5 / SQL Server 2012 并且我有以下类:

public partial class Topic {
    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 int SubTopicId { get; set; }
    public string Name { get; set; }
    public int TopicId { get; set; }
    public virtual Topic Topic { get; set; }
    public virtual ICollection<Question> Questions { get; set; }
}

public class Question {
    public int QuestionId { get; set; }
    public int QuestionStatusId { get; set; }
    public string Title { get; set; }
    public string Text { get; set; }
    public int SubTopicId { get; set; }
    public virtual SubTopic SubTopic { get; set; }
    public virtual ICollection<Answer> Answers { get; set; }
}

我正在使用以下内容来获取问题详细信息:

    public IList<Question> GetQuestionsUser(int userId, int questionStatusId) {
        var questions = _questionsRepository.GetAll()
            .Include(a => a.Answers)
            .ToList();
        return questions;
    }

现在我还想返回以下两个字段并按 SubjectId 过滤

  • 主题.名称
  • 子主题名称

我知道我可以在 Linq 中包含下来,因为我用它来获取答案。但是,我可以编写我的 Linq 查询以获取 Topic.Name、SubTopic.Name 并按 SubjectId 过滤吗?

对不起,如果这听起来像是我在要求某人为我做我的工作。但是,我只想获得一些想法,所以一旦我知道如何去做,我就可以将其应用于我的其他类似需求。

4

1 回答 1

5
 //assuming your repo GetAll() returns a DbQuery<T>
 var questions = _questionsRepository.GetAll()
                .Where(q=>q.SubTopic.Topic.SubjectId = mySubjectId)
                .Include(q=>q.Answers)
                .Include(q=>q.SubTopic.Topic)
                .ToList();
于 2013-07-25T08:28:50.163 回答