簡體   English   中英

如何創建連接四個表並在最上面的表中允許一個LINQ表達式?

[英]How can I create a LINQ expression that joins four tables and allows a where on the topmost table?

我有以下課程:

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;

您具有所需的所有導航屬性,因此您可以執行以下操作:

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM