获取学生列表

在学生列表中,不仅要显示学生的基本信息,还要显示班级名称,专业名称,年级。

因此需要通过Include方法加载数据。

但是,仅仅使用一层Include方法是不够的,这样只能获取到ClassName。

还需要使用ThenInclude获取MajorName和GradeN。

添加GetListWithMajorAndGradeAndClass方法

在StudentRepo中添加GetListWithMajorAndGradeAndClass方法。

代码如下:

public List<Student> GetListWithMajorAndGradeAndClass()
{
    return DbSet
        .Include(s => s.Class).ThenInclude(c => c.Major)
        .Include(s => s.Class).ThenInclude(c => c.Grade)
        .ToList();
}

DbSet先通过Include(s => s.Class)加载班级的数据,再通过ThenInclude(c => c.Major)ThenInclude(c => c.Grade)加载专业和年级的数据。

注意,不能直接写DbSet.Include(s => s.Class).ThenInclude(c => c.Major).ThenInclude(c => c.Grade).ToList();

创建GetList方法

在StudentService中创建GetList方法,代码如下:

public List<StudentViewModel> GetList()
{
    List<Student> students = studentRepo.GetListWithMajorAndGradeAndClass();
    List<StudentViewModel> studentViewModels = new List<StudentViewModel>();
    foreach (var student in students)
    {
        studentViewModels.Add(new StudentViewModel()
        {
            Id = student.Id,
            Number = student.Number,
            Name = student.Name,
            Gender = student.Gender,
            Birthday = student.Birthday,
            ClassName = student.Class.Name,
            MajorName = student.Class.Major.Name,
            GradeName = student.Class.Grade.Name,
        });
    }
    return studentViewModels;
}

传递视图模型列表

在StudentController的Index方法中将视图模型列表传递给视图,代码如下:

public IActionResult Index()
{
    return View(studentService.GetList());
}

创建Index视图

创建Index.cshtml视图,代码如下:

@{
    ViewBag.Title = "学生管理";
}
@model List<StudentViewModel>

<div>
    <a asp-action="Add" class="button is-primary mb-4">添加学生</a>
    <table class="table is-bordered is-striped is-hoverable is-fullwidth">
        <thead>
            <tr>
                <th>学号</th>
                <th>姓名</th>
                <th>专业</th>
                <th>年级</th>
                <th>班级</th>                
                <th>性别</th>
                <th>生日</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var student in Model)
            {
                <tr>
                    <td>@student.Number</td>
                    <td>@student.Name</td>
                    <td>@student.MajorName</td>
                    <td>@student.GradeName</td>
                    <td>@student.ClassName</td>                    
                    <td>@(student.Gender ? "女" : "男")</td>
                    <td>@student.Birthday.ToString("yyyy年MM月dd日")</td>
                    <td>
                        <a asp-action="Edit" asp-route-id="@student.Id" class="button is-warning">编辑</a>
                    </td>
                </tr>
            }
        </tbody>
    </table>
</div>

其中,@(student.Gender?"女":"男"),表示如果student.Gender的值为true,则显示,否则显示

@student.Birthday.ToString("yyyy年MM月dd日")表示将日期格式化为yyyy年MM月dd日的形式。