代码中遇到的问题:
包含课程的主题[],然后包含主题的问题[]后,播放中的实体现在变成了问题。所需的行为还包括 Topic 的 SubTopic[] 和 SubTopic 的 Question[]。
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# 中所需的对象表示:
每次您想从顶部开始时,您只需一次又一次地包含即可。在你的情况下,它会是
include topic
theninclude questions
theninclude answers
include topic
theninclude topic