第 2 部分,在 ASP.NET Core 中向 Razor 页面应用添加模型Part 2, add a model to a Razor Pages app in ASP.NET Core

作者:Rick AndersonBy Rick Anderson

在该部分,会添加类管理影片。In this section, classes are added for managing movies. 应用的模型类使用 Entity Framework Core (EF Core) 来处理数据库。The app's model classes use Entity Framework Core (EF Core) to work with the database. EF Core 是一种对象关系映射器 (ORM),可简化数据访问。EF Core is an object-relational mapper (O/RM) that simplifies data access.

模型类称为 POCO 类(源自“简单传统 CLR 对象”),因为它们与 EF Core 没有任何依赖关系。The model classes are known as POCO classes (from "plain-old CLR objects") because they don't have any dependency on EF Core. 它们定义数据库中存储的数据属性。They define the properties of the data that are stored in the database.

添加数据模型Add a data model

右键单击“RazorPagesMovie”项目 >“添加” > “新建文件夹”。Right-click the RazorPagesMovie project > Add > New Folder. 将文件夹命名为“Models”。Name the folder Models.

右键单击“Models”文件夹。Right click the Models folder. 选择“添加” > “类” 。Select Add > Class. 将类命名“Movie”。Name the class Movie.

Movie 类添加以下属性:Add the following properties to the Movie class:

using System;
using System.ComponentModel.DataAnnotations;

namespace RazorPagesMovie.Models
{
    public class Movie
    {
        public int ID { get; set; }
        public string Title { get; set; }

        [DataType(DataType.Date)]
        public DateTime ReleaseDate { get; set; }
        public string Genre { get; set; }
        public decimal Price { get; set; }
    }
}

Movie 类包含:The Movie class contains:

  • 数据库需要 ID 字段以获取主键。The ID field is required by the database for the primary key.

  • [DataType(DataType.Date)]DataType 属性指定数据的类型(日期)。[DataType(DataType.Date)]: The DataType attribute specifies the type of the data (Date). 通过此特性:With this attribute:

    • 用户无需在数据字段中输入时间信息。The user is not required to enter time information in the date field.
    • 仅显示日期,而非时间信息。Only the date is displayed, not time information.

DataAnnotations 会在后续教程中介绍。DataAnnotations are covered in a later tutorial.

生成项目以验证没有任何编译错误。Build the project to verify there are no compilation errors.

搭建“电影”模型的基架Scaffold the movie model

在此部分,将搭建“电影”模型的基架。In this section, the movie model is scaffolded. 确切地说,基架工具将生成页面,用于对“电影”模型执行创建、读取、更新和删除 (CRUD) 操作。That is, the scaffolding tool produces pages for Create, Read, Update, and Delete (CRUD) operations for the movie model.

创建“Pages/Movies”文件夹:Create a Pages/Movies folder:

  • 右键单击“Pages”文件夹 >“添加”>“新建文件夹”。Right click on the Pages folder > Add > New Folder.
  • 将文件夹命名为“Movies”Name the folder Movies

右键单击“Pages/Movies”文件夹 >“添加”>“新搭建基架的项目”。Right click on the Pages/Movies folder > Add > New Scaffolded Item.

上述说明的图像。

在“添加基架”对话框中,依次选择“使用实体框架的 Razor 页面 (CRUD)”>“添加”。 In the Add Scaffold dialog, select Razor Pages using Entity Framework (CRUD) > Add.

上述说明的图像。

完成“添加使用实体框架的 Razor 页面 (CRUD)”对话框:Complete the Add Razor Pages using Entity Framework (CRUD) dialog:

  • 在“模型类”下拉列表中,选择“Movie (RazorPagesMovie.Models) 。In the Model class drop down, select Movie (RazorPagesMovie.Models).
  • 在“数据上下文类”行中,选择 +(加号)并将生成的名称从 RazorPagesMovie.Models.RazorPagesMovieContext 更改为 RazorPagesMovie.Data.RazorPagesMovieContext 。In the Data context class row, select the + (plus) sign and change the generated name from RazorPagesMovie.Models.RazorPagesMovieContext to RazorPagesMovie.Data.RazorPagesMovieContext. 不需要此更新This change is not required. 它创建具有正确命名空间的数据库上下文类。It creates the database context class with the correct namespace.
  • 选择“添加”。Select Add.

上述说明的图像。

appsettings.json 文件通过用于连接到本地数据的连接字符串进行更新。The appsettings.json file is updated with the connection string used to connect to a local database.

创建的文件Files created

在搭建基架时,会创建并更新以下文件:The scaffold process creates and updates the following files:

  • Pages/Movies:“创建”、“删除”、“详细信息”、“编辑”和“索引”。Pages/Movies: Create, Delete, Details, Edit, and Index.
  • Data/RazorPagesMovieContext.csData/RazorPagesMovieContext.cs

已更新Updated

  • Startup.csStartup.cs

创建和更新的文件将在下一节中说明。The created and updated files are explained in the next section.

初始迁移Initial migration

在此部分中,程序包管理器控制台 (PMC) 用于:In this section, the Package Manager Console (PMC) is used to:

  • 添加初始迁移。Add an initial migration.
  • 使用初始迁移来更新数据库。Update the database with the initial migration.

从“工具”菜单中,选择“NuGet 包管理器”>“包管理器控制台” 。From the Tools menu, select NuGet Package Manager > Package Manager Console.

PMC 菜单

在 PMC 中,输入以下命令:In the PMC, enter the following commands:

Add-Migration InitialCreate
Update-Database

前面的命令生成以下警告:“No type was specified for the decimal column 'Price' on entity type 'Movie'.The preceding commands generate the following warning: "No type was specified for the decimal column 'Price' on entity type 'Movie'. This will cause values to be silently truncated if they do not fit in the default precision and scale.This will cause values to be silently truncated if they do not fit in the default precision and scale. Explicitly specify the SQL server column type that can accommodate all the values using 'HasColumnType()'.”Explicitly specify the SQL server column type that can accommodate all the values using 'HasColumnType()'."

你可以忽略该警告,它将后面的教程中得到修复。You can ignore that warning, it will be fixed in a later tutorial.

migrations 命令生成用于创建初始数据库架构的代码。The migrations command generates code to create the initial database schema. 该架构基于在 DbContext 中指定的模型。The schema is based on the model specified in DbContext. InitialCreate 参数用于为迁移命名。The InitialCreate argument is used to name the migrations. 可以使用任何名称,但是按照惯例,会选择可说明迁移的名称。Any name can be used, but by convention a name is selected that describes the migration.

update 命令在尚未应用的迁移中运行 Up 方法。The update command runs the Up method in migrations that have not been applied. 在这种情况下,update 在用于创建数据库的 Migrations/<time-stamp>_InitialCreate.cs 文件中运行 Up 方法。In this case, update runs the Up method in Migrations/<time-stamp>_InitialCreate.cs file, which creates the database.

检查通过依赖关系注入注册的上下文Examine the context registered with dependency injection

ASP.NET Core 通过依赖关系注入进行生成。ASP.NET Core is built with dependency injection. 服务(例如 EF Core 数据库上下文)在应用程序启动期间通过依赖关系注入进行注册。Services (such as the EF Core DB context) are registered with dependency injection during application startup. 需要这些服务(如 Razor 页面)的组件通过构造函数参数提供相应服务。Components that require these services (such as Razor Pages) are provided these services via constructor parameters. 本教程的后续部分介绍了用于获取 DB 上下文实例的构造函数代码。The constructor code that gets a DB context instance is shown later in the tutorial.

基架工具自动创建 DB 上下文并将其注册到依赖关系注入容器。The scaffolding tool automatically created a DB context and registered it with the dependency injection container.

检查 Startup.ConfigureServices 方法。Examine the Startup.ConfigureServices method. 基架添加了突出显示的行:The highlighted line was added by the scaffolder:

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();

    services.AddDbContext<RazorPagesMovieContext>(options =>
      options.UseSqlServer(Configuration.GetConnectionString("RazorPagesMovieContext")));
}

RazorPagesMovieContextMovie 模型协调 EF Core 功能(创建、读取、更新、删除等)。The RazorPagesMovieContext coordinates EF Core functionality (Create, Read, Update, Delete, etc.) for the Movie model. 数据上下文 (RazorPagesMovieContext) 派生自 Microsoft.EntityFrameworkCore.DbContextThe data context (RazorPagesMovieContext) is derived from Microsoft.EntityFrameworkCore.DbContext. 数据上下文指定数据模型中包含哪些实体。The data context specifies which entities are included in the data model.

using Microsoft.EntityFrameworkCore;

namespace RazorPagesMovie.Models
{
    public class RazorPagesMovieContext : DbContext
    {
        public RazorPagesMovieContext (DbContextOptions<RazorPagesMovieContext> options)
            : base(options)
        {
        }

        public DbSet<RazorPagesMovie.Models.Movie> Movie { get; set; }
    }
}

前面的代码为实体集创建 DbSet<Movie> 属性。The preceding code creates a DbSet<Movie> property for the entity set. 在实体框架术语中,实体集通常与数据表相对应。In Entity Framework terminology, an entity set typically corresponds to a database table. 实体对应表中的行。An entity corresponds to a row in the table.

通过调用 DbContextOptions 对象中的一个方法将连接字符串名称传递到上下文。The name of the connection string is passed in to the context by calling a method on a DbContextOptions object. 进行本地开发时, ASP.NET Core 配置系统appsettings.json 文件中读取数据库连接字符串。For local development, the ASP.NET Core configuration system reads the connection string from the appsettings.json file.

测试应用Test the app

  • 运行应用并将 /Movies 追加到浏览器中的 URL (http://localhost:port/movies)。Run the app and append /Movies to the URL in the browser (http://localhost:port/movies).

如果收到错误:If you get the error:

SqlException: Cannot open database "RazorPagesMovieContext-GUID" requested by the login. The login failed.
Login failed for user 'User-name'.

缺少迁移步骤You missed the migrations step.

  • 测试“创建”链接。Test the Create link.

    创建页面

    备注

    可能无法在 Price 字段中输入十进制逗号。You may not be able to enter decimal commas in the Price field. 若要使 jQuery 验证支持使用逗号(“,”)表示小数点的非英语区域设置,以及支持非美国英语日期格式,应用必须进行全球化。To support jQuery validation for non-English locales that use a comma (",") for a decimal point and for non US-English date formats, the app must be globalized. 有关全球化的说明,请参阅此 GitHub 问题For globalization instructions, see this GitHub issue.

  • 测试“编辑”、“详细信息”和“删除”链接。Test the Edit, Details, and Delete links.

下一个教程介绍由基架创建的文件。The next tutorial explains the files created by scaffolding.

其他资源Additional resources

在本节中,添加了用于管理跨平台 SQLite 数据库中的电影的类。In this section, classes are added for managing movies in a cross-platform SQLite database. 从 ASP.NET Core 模板创建的应用使用 SQLite 数据库。Apps created from an ASP.NET Core template use a SQLite database. 应用的模型类配合 Entity Framework Core (EF Core)SQLite EF Core 数据库提供程序)使用,以处理数据库。The app's model classes are used with Entity Framework Core (EF Core) (SQLite EF Core Database Provider) to work with the database. EF Core 是一种对象关系映射 (ORM) 框架,可以简化数据访问。EF Core is an object-relational mapping (ORM) framework that simplifies data access.

模型类称为 POCO 类(源自“简单传统 CLR 对象”),因为它们与 EF Core 没有任何依赖关系。The model classes are known as POCO classes (from "plain-old CLR objects") because they don't have any dependency on EF Core. 它们定义数据库中存储的数据属性。They define the properties of the data that are stored in the database.

添加数据模型Add a data model

右键单击“RazorPagesMovie”项目 >“添加” > “新建文件夹”。Right-click the RazorPagesMovie project > Add > New Folder. 将文件夹命名为“Models”。Name the folder Models.

右键单击“Models”文件夹。Right click the Models folder. 选择“添加” > “类” 。Select Add > Class. 将类命名“Movie”。Name the class Movie.

Movie 类添加以下属性:Add the following properties to the Movie class:

using System;
using System.ComponentModel.DataAnnotations;

namespace RazorPagesMovie.Models
{
    public class Movie
    {
        public int ID { get; set; }
        public string Title { get; set; }

        [DataType(DataType.Date)]
        public DateTime ReleaseDate { get; set; }
        public string Genre { get; set; }
        public decimal Price { get; set; }
    }
}

Movie 类包含:The Movie class contains:

  • 数据库需要 ID 字段以获取主键。The ID field is required by the database for the primary key.

  • [DataType(DataType.Date)]DataType 属性指定数据的类型(日期)。[DataType(DataType.Date)]: The DataType attribute specifies the type of the data (Date). 通过此特性:With this attribute:

    • 用户无需在数据字段中输入时间信息。The user is not required to enter time information in the date field.
    • 仅显示日期,而非时间信息。Only the date is displayed, not time information.

DataAnnotations 会在后续教程中介绍。DataAnnotations are covered in a later tutorial.

生成项目以验证没有任何编译错误。Build the project to verify there are no compilation errors.

搭建“电影”模型的基架Scaffold the movie model

在此部分,将搭建“电影”模型的基架。In this section, the movie model is scaffolded. 确切地说,基架工具将生成页面,用于对“电影”模型执行创建、读取、更新和删除 (CRUD) 操作。That is, the scaffolding tool produces pages for Create, Read, Update, and Delete (CRUD) operations for the movie model.

创建“Pages/Movies”文件夹:Create a Pages/Movies folder:

  • 右键单击“Pages”文件夹 >“添加”>“新建文件夹”。Right click on the Pages folder > Add > New Folder.
  • 将文件夹命名为“Movies”Name the folder Movies

右键单击“Pages/Movies”文件夹 >“添加”>“新搭建基架的项目”。Right click on the Pages/Movies folder > Add > New Scaffolded Item.

上述说明的图像。

在“添加基架”对话框中,依次选择“使用实体框架的 Razor 页面 (CRUD)”>“添加”。 In the Add Scaffold dialog, select Razor Pages using Entity Framework (CRUD) > Add.

上述说明的图像。

完成“添加使用实体框架的 Razor 页面 (CRUD)”对话框:Complete the Add Razor Pages using Entity Framework (CRUD) dialog:

  • 在“模型类”下拉列表中,选择“Movie (RazorPagesMovie.Models) 。In the Model class drop down, select Movie (RazorPagesMovie.Models).
  • 在“数据上下文类”行中,选择 +(加号)并接受生成的名称“RazorPagesMovie.Models.RazorPagesMovieContext” 。In the Data context class row, select the + (plus) sign and accept the generated name RazorPagesMovie.Models.RazorPagesMovieContext.
  • 选择“添加”。Select Add.

上述说明的图像。

appsettings.json 文件通过用于连接到本地数据的连接字符串进行更新。The appsettings.json file is updated with the connection string used to connect to a local database.

在搭建基架时,会创建并更新以下文件:The scaffold process creates and updates the following files:

创建的文件Files created

  • Pages/Movies:“创建”、“删除”、“详细信息”、“编辑”和“索引”。Pages/Movies: Create, Delete, Details, Edit, and Index.
  • Data/RazorPagesMovieContext.csData/RazorPagesMovieContext.cs

文件已更新File updated

  • Startup.csStartup.cs

创建和更新的文件将在下一节中说明。The created and updated files are explained in the next section.

初始迁移Initial migration

在此部分中,程序包管理器控制台 (PMC) 用于:In this section, the Package Manager Console (PMC) is used to:

  • 添加初始迁移。Add an initial migration.
  • 使用初始迁移来更新数据库。Update the database with the initial migration.

从“工具”菜单中,选择“NuGet 包管理器”>“包管理器控制台” 。From the Tools menu, select NuGet Package Manager > Package Manager Console.

PMC 菜单

在 PMC 中,输入以下命令:In the PMC, enter the following commands:

Add-Migration Initial
Update-Database

Add-Migration 命令生成用于创建初始数据库架构的代码。The Add-Migration command generates code to create the initial database schema. 此架构的依据为 DbContext 中指定的模型(在 RazorPagesMovieContext.cs 文件中)。The schema is based on the model specified in the DbContext (In the RazorPagesMovieContext.cs file). InitialCreate 参数用于为迁移命名。The InitialCreate argument is used to name the migration. 可以使用任何名称,但是按照惯例,会使用可说明迁移的名称。Any name can be used, but by convention a name that describes the migration is used. 有关详细信息,请参阅 教程:使用迁移功能 - ASP.NET MVC 和 EF CoreFor more information, see 教程:使用迁移功能 - ASP.NET MVC 和 EF Core.

Update-Database 命令在 Migrations/<time-stamp>_InitialCreate.cs 文件中运行 Up 方法。The Update-Database command runs the Up method in the Migrations/<time-stamp>_InitialCreate.cs file. Up 方法会创建数据库。The Up method creates the database.

备注

前面的命令生成以下警告:"No type was specified for the decimal column 'Price' on entity type 'Movie'.This will cause values to be silently truncated if they do not fit in the default precision and scale.Explicitly specify the SQL server column type that can accommodate all the values using 'HasColumnType()'. " 你可以忽略该警告,它将后面的教程中得到修复。The preceding commands generate the following warning: "No type was specified for the decimal column 'Price' on entity type 'Movie'. This will cause values to be silently truncated if they do not fit in the default precision and scale. Explicitly specify the SQL server column type that can accommodate all the values using 'HasColumnType()'." You can ignore that warning, it will be fixed in a later tutorial.

检查通过依赖关系注入注册的上下文Examine the context registered with dependency injection

ASP.NET Core 通过依赖关系注入进行生成。ASP.NET Core is built with dependency injection. 服务(例如 EF Core 数据库上下文)在应用程序启动期间通过依赖关系注入进行注册。Services (such as the EF Core DB context) are registered with dependency injection during application startup. 需要这些服务(如 Razor 页面)的组件通过构造函数参数提供相应服务。Components that require these services (such as Razor Pages) are provided these services via constructor parameters. 本教程的后续部分介绍了用于获取 DB 上下文实例的构造函数代码。The constructor code that gets a DB context instance is shown later in the tutorial.

基架工具自动创建 DB 上下文并将其注册到依赖关系注入容器。The scaffolding tool automatically created a DB context and registered it with the dependency injection container.

检查 Startup.ConfigureServices 方法。Examine the Startup.ConfigureServices method. 基架添加了突出显示的行:The highlighted line was added by the scaffolder:

// This method gets called by the runtime. 
// Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is 
        // needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    services.AddDbContext<RazorPagesMovieContext>(options =>
      options.UseSqlServer(
          Configuration.GetConnectionString("RazorPagesMovieContext")));
}

RazorPagesMovieContextMovie 模型协调 EF Core 功能(创建、读取、更新、删除等)。The RazorPagesMovieContext coordinates EF Core functionality (Create, Read, Update, Delete, etc.) for the Movie model. 数据上下文 (RazorPagesMovieContext) 派生自 Microsoft.EntityFrameworkCore.DbContextThe data context (RazorPagesMovieContext) is derived from Microsoft.EntityFrameworkCore.DbContext. 数据上下文指定数据模型中包含哪些实体。The data context specifies which entities are included in the data model.

using Microsoft.EntityFrameworkCore;

namespace RazorPagesMovie.Models
{
    public class RazorPagesMovieContext : DbContext
    {
        public RazorPagesMovieContext (DbContextOptions<RazorPagesMovieContext> options)
            : base(options)
        {
        }

        public DbSet<RazorPagesMovie.Models.Movie> Movie { get; set; }
    }
}

前面的代码为实体集创建 DbSet<Movie> 属性。The preceding code creates a DbSet<Movie> property for the entity set. 在实体框架术语中,实体集通常与数据表相对应。In Entity Framework terminology, an entity set typically corresponds to a database table. 实体对应表中的行。An entity corresponds to a row in the table.

通过调用 DbContextOptions 对象中的一个方法将连接字符串名称传递到上下文。The name of the connection string is passed in to the context by calling a method on a DbContextOptions object. 进行本地开发时, ASP.NET Core 配置系统appsettings.json 文件中读取数据库连接字符串。For local development, the ASP.NET Core configuration system reads the connection string from the appsettings.json file.

测试应用Test the app

  • 运行应用并将 /Movies 追加到浏览器中的 URL (http://localhost:port/movies)。Run the app and append /Movies to the URL in the browser (http://localhost:port/movies).

如果收到错误:If you get the error:

SqlException: Cannot open database "RazorPagesMovieContext-GUID" requested by the login. The login failed.
Login failed for user 'User-name'.

缺少迁移步骤You missed the migrations step.

  • 测试“创建”链接。Test the Create link.

    创建页面

    备注

    可能无法在 Price 字段中输入十进制逗号。You may not be able to enter decimal commas in the Price field. 若要使 jQuery 验证支持使用逗号(“,”)表示小数点的非英语区域设置,以及支持非美国英语日期格式,应用必须进行全球化。To support jQuery validation for non-English locales that use a comma (",") for a decimal point and for non US-English date formats, the app must be globalized. 有关全球化的说明,请参阅此 GitHub 问题For globalization instructions, see this GitHub issue.

  • 测试“编辑”、“详细信息”和“删除”链接。Test the Edit, Details, and Delete links.

下一个教程介绍由基架创建的文件。The next tutorial explains the files created by scaffolding.

其他资源Additional resources