为简单起见,我有3个实体(一对多,从左到右):
课程 - > MODULE - >章
一门课程可以有多个模块,一个模块可以有多个章节。
我在控制器中的所有内容都是:
Course course = db.Courses.Find(id);
return View(course);
我试图使用包含但似乎没有评估(这似乎不起作用:Course course = db.Courses.Include("Modules").Find(id);
)
所以我放手了。在我看来,我有这个嵌套的List:
<ul>
@foreach (var item in Model.Modules)
{
<li>@module.Title
<ul>
@foreach (var item in module.Chapters)
{
<li>@chapter.Title</li>
}
</ul>
</li>
}
</ul>
这会自动生效吗?
最后,我应用了一个SortOrder列,以便我可以安排子实体。我知道这应该在查询中完成,但我该怎么做呢?
谢谢!任何信息或建议都将受到高度赞赏。
更新
课程类
public partial class Course
{
public Course()
{
this.Modules = new HashSet<Module>();
this.Assets = new HashSet<Asset>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Author { get; set; }
public System.DateTime CreateDate { get; set; }
public bool IsDeleted { get; set; }
public int IndustryId { get; set; }
public virtual ICollection<Module> Modules { get; set; }
public virtual ICollection<Asset> Assets { get; set; }
public virtual Industry Industry { get; set; }
}
模块类
namespace RocketLabs.Models
{
using System;
using System.Collections.Generic;
public partial class Module
{
public Module()
{
this.Chapters = new HashSet<Chapter>();
this.Assets = new HashSet<Asset>();
}
public int Id { get; set; }
public string Title { get; set; }
public System.DateTime CreateDate { get; set; }
public int CourseId { get; set; }
public bool IsDeleted { get; set; }
public short SortOrder { get; set; }
public virtual Course Course { get; set; }
public virtual ICollection<Chapter> Chapters { get; set; }
public virtual ICollection<Asset> Assets { get; set; }
public virtual Exam Exam { get; set; }
}
}
章节
namespace RocketLabs.Models
{
using System;
using System.Collections.Generic;
public partial class Chapter
{
public Chapter()
{
this.Assets = new HashSet<Asset>();
}
public int Id { get; set; }
public string Title { get; set; }
public int ModuleId { get; set; }
public string Notes { get; set; }
public short SortOrder { get; set; }
public System.DateTime CreateDate { get; set; }
public bool IsDeleted { get; set; }
public virtual Module Module { get; set; }
public virtual ICollection<Asset> Assets { get; set; }
}
}
答案 0 :(得分:2)
你可以这样做:
var course = db.Courses
.Include(i => i.Modules.Select(s => s.Chapter))
.Single(s=>s.Id == id);
return View(course);
你的循环:
<ul>
@foreach (var module in Model.Modules)
{
<li>@module.Title
<ul>
@foreach (var chapter in module.Chapters)
{
<li>@chapter.Title</li>
}
</ul>
</li>
}
</ul>
至于排序,我们可以在您的查询中包含.OrderBy(),但您需要详细说明您想要排序的子实体以及哪些字段。