系列文章目录:系列教程:使用 Core创建Razor Pages Web应用程序 - zhangpeterx的博客
系列教程代码的GitHub地址:ASP .Net Core Razor Pages MySQL Tutorial
上一个教程: Core Web Razor Pages系列教程六:添加搜索功能
打开Models / Movie.cs文件并添加Rating属性:
修改后代码如下:
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using ponentModel.DataAnnotations;using ponentModel.DataAnnotations.Schema;namespace RazorPagesMovie.Models{public class Movie{public int ID {get; set; }public string Title {get; set; }[Display(Name = "Release Date")][DataType(DataType.Date)]public DateTime ReleaseDate {get; set; }public string Genre {get; set; }[Column(TypeName = "decimal(18, 2)")]public decimal Price {get; set; }public string Rating {get; set; }}}
编辑Pages / Movies / Index.cshtml,在<thead>
中添加一个Rating字段:
<th>@Html.DisplayNameFor(model => model.Movie[0].Rating)</th>
在<tbody>
中添加:
<td>@Html.DisplayFor(modelItem => item.Rating)</td>
因为你修改了数据库的模型,因此就的模型不能用了。
我们选择使用Code First Migrations更新数据库架构。
修改Models/SeedData.cs
,添加属性:
Rating = "R"
然后进行数据迁移。
从“ 工具”菜单中,选择“ NuGet包管理器” >“ 包管理器控制台”。
输入如下命令:
Add-Migration RatingUpdate-Database
该Add-Migration命令告诉框架:
将Movie模型与Movie数据库模式进行比较。创建代码以将数据库模式迁移到新模型。
名称“Rating”是任意的,用于命名迁移文件。为迁移文件使用有意义的名称会很有帮助。
该Update-Database命令告诉框架将架构更改应用于数据库。
然后运行程序:
数据库迁移成功。
下一个教程: Core Web Razor Pages系列教程八: 添加验证