如何编写 EF Core 查询来实现具有自引用子级的正确实体层次结构?

问题描述 投票:0回答:1

代码中遇到的问题:

包含课程主题[],然后包含主题问题[]后,播放中的实体现在变成了问题。所需的行为还包括 TopicSubTopic[] 和 SubTopicQuestion[]。

  • 不太重要(这可以在前端解决,但保持对象大小较小更好):不要包含与Topic同一级别的SubTopic[],这是当前的行为(应该Topic .CourseId 可以为空吗?)
public async Task<ActionResult<Course>> GetCourse(int id)
{
    var course = await _context.Courses
        .Include(course => course.Topics)
        .ThenInclude(topic => topic.Questions)
        //.ThenInclude(topic => topic.SubTopics) // lambda param here is a Question, not Topic
        //.ThenInclude(subTopic => subTopic.Questions)
        .ThenInclude(question => question.Answers)
        .FirstOrDefaultAsync(c => c.Id == id);

    if (course == null)
    {
        return NotFound();
    }

    return course;
}

实体架构:

public class Course
 {
     public int Id { get; set; }
     public string Name { get; set; }
     public string Description { get; set; }
     public ICollection<Topic> Topics { get; } = new List<Topic>();

 }
public class Topic
{
    public int Id { get; set; }
    public int CourseId { get; set; }
    public Course Course { get; set; } = null;
    public int? TopicId { get; set; } // self-referential; this makes it a SubTopic
    public Topic ParentTopic { get; set; } = null;
    public string Name { get; set; }
    public string Description { get; set; }        
    public ICollection<Topic> SubTopics { get; set; } = new List<Topic>();
    public ICollection<Question> Questions { get; set; } = new List<Question>();

}

迁移后的数据库:

C# 中所需的对象表示:

c# entity-framework
1个回答
0
投票

每次您想从顶部开始时,您只需一次又一次地包含即可。在你的情况下,它会是

include topic
theninclude questions
theninclude answers
include topic
theninclude topic
© www.soinside.com 2019 - 2024. All rights reserved.