我正在使用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过滤?
很抱歉,如果这听起来像我要求有人为我做我的工作。但是我想得到一些想法,所以一旦我知道如何做到这一点,我可以将其应用于我所拥有的其他类似需求。
答案 0 :(得分: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();