使用 Code First 迁移对数据库进行种子设定Use Code First Migrations to Seed the Database

作者: Mike Wassonby Mike Wasson

下载完成的项目Download Completed Project

在本部分中,你将使用 EF 中的Code First 迁移来使用测试数据为数据库提供种子。In this section, you will use Code First Migrations in EF to seed the database with test data.

从 "工具" 菜单中,选择 " NuGet 包管理器",然后选择 "程序包管理器控制台"。From the Tools menu, select NuGet Package Manager, then select Package Manager Console. 在“Package Manager Console”窗口中,输入以下命令:In the Package Manager Console window, enter the following command:

Enable-Migrations

此命令将名为迁移的文件夹添加到你的项目中,并在迁移文件夹中添加名为 Configuration.cs 的代码文件。This command adds a folder named Migrations to your project, plus a code file named Configuration.cs in the Migrations folder.

打开 Configuration.cs 文件。Open the Configuration.cs file. 添加以下using语句。Add the following using statement.

using BookService.Models;

然后,将以下代码添加到配置. Seed方法:Then add the following code to the Configuration.Seed method:

protected override void Seed(BookService.Models.BookServiceContext context)
{
    context.Authors.AddOrUpdate(x => x.Id,
        new Author() { Id = 1, Name = "Jane Austen" },
        new Author() { Id = 2, Name = "Charles Dickens" },
        new Author() { Id = 3, Name = "Miguel de Cervantes" }
        );

    context.Books.AddOrUpdate(x => x.Id,
        new Book() { Id = 1, Title = "Pride and Prejudice", Year = 1813, AuthorId = 1, 
            Price = 9.99M, Genre = "Comedy of manners" },
        new Book() { Id = 2, Title = "Northanger Abbey", Year = 1817, AuthorId = 1, 
            Price = 12.95M, Genre = "Gothic parody" },
        new Book() { Id = 3, Title = "David Copperfield", Year = 1850, AuthorId = 2, 
            Price = 15, Genre = "Bildungsroman" },
        new Book() { Id = 4, Title = "Don Quixote", Year = 1617, AuthorId = 3, 
            Price = 8.95M, Genre = "Picaresque" }
        );
}

在 "程序包管理器控制台" 窗口中,键入以下命令:In the Package Manager Console window, type the following commands:

Add-Migration Initial
Update-Database

第一个命令生成用于创建数据库的代码,第二个命令执行该代码。The first command generates code that creates the database, and the second command executes that code. 使用LocalDB在本地创建数据库。The database is created locally, using LocalDB.

探索 API (可选)Explore the API (Optional)

按 F5 以调试模式运行应用程序。Press F5 to run the application in debug mode. Visual Studio 将启动 IIS Express 并运行你的 web 应用。Visual Studio starts IIS Express and runs your web app. 然后,Visual Studio 会启动浏览器并打开应用程序的主页。Visual Studio then launches a browser and opens the app's home page.

当 Visual Studio 运行 web 项目时,它会分配一个端口号。When Visual Studio runs a web project, it assigns a port number. 在下图中,端口号为50524。In the image below, the port number is 50524. 运行应用程序时,将看到不同的端口号。When you run the application, you'll see a different port number.

主页是使用 ASP.NET MVC 实现的。The home page is implemented using ASP.NET MVC. 页面顶部有一个链接,其中显示了 "API"。At the top of the page, there is a link that says "API". 此链接可为您提供 web API 自动生成的帮助页。This link brings you to an auto-generated help page for the web API. (若要了解如何生成此帮助页,以及如何向页面添加您自己的文档,请参阅为 ASP.NET Web API 创建帮助页。)你可以单击 "帮助" 页链接来查看有关 API 的详细信息,包括请求和响应格式。(To learn how this help page is generated, and how you can add your own documentation to the page, see Creating Help Pages for ASP.NET Web API.) You can click on the help page links to see details about the API, including the request and response format.

API 对数据库启用 CRUD 操作。The API enables CRUD operations on the database. 下面概述了 API。The following summarizes the API.

AuthorsAuthors
GET api/authorsGET api/authors 获取所有作者。Get all authors.
GET api/authors/{id}GET api/authors/{id} 按 ID 获取作者。Get an author by ID.
POST /api/authorsPOST /api/authors 创建新的作者。Create a new author.
PUT /api/authors/{id}PUT /api/authors/{id} 更新现有的作者。Update an existing author.
DELETE /api/authors/{id}DELETE /api/authors/{id} 删除作者。Delete an author.
图书Books
GET /api/booksGET /api/books 获取所有书籍。Get all books.
GET /api/books/{id}GET /api/books/{id} 按 ID 获取书籍。Get a book by ID.
POST /api/booksPOST /api/books 创建新书籍。Create a new book.
PUT /api/books/{id}PUT /api/books/{id} 更新现有书籍。Update an existing book.
DELETE /api/books/{id}DELETE /api/books/{id} 删除书籍。Delete a book.

查看数据库(可选)View the Database (Optional)

运行 "更新-数据库" 命令时,EF 会创建数据库,并将其称为 Seed 方法。When you ran the Update-Database command, EF created the database and called the Seed method. 在本地运行应用程序时,EF 使用LocalDBWhen you run the application locally, EF uses LocalDB. 您可以在 Visual Studio 中查看数据库。You can view the database in Visual Studio. 从“视图”菜单上,选择“SQL Server 对象资源管理器”。From the View menu, select SQL Server Object Explorer.

在 "连接到服务器" 对话框的 "服务器名称" 编辑框中,键入 "(localdb) \v11.0"。In the Connect to Server dialog, in the Server Name edit box, type "(localdb)\v11.0". 将 "身份验证" 选项保留为 "Windows 身份验证"。Leave the Authentication option as "Windows Authentication". 单击“连接”。Click Connect.

Visual Studio 连接到 LocalDB,并在 "SQL Server 对象资源管理器" 窗口中显示现有的数据库。Visual Studio connects to LocalDB and shows your existing databases in the SQL Server Object Explorer window. 您可以展开节点以查看 EF 创建的表。You can expand the nodes to see the tables that EF created.

若要查看数据,请右键单击表并选择 "查看数据"。To view the data, right-click a table and select View Data.

以下屏幕截图显示了 Books.xml 表的结果。The following screenshot shows the results for the Books table. 请注意,EF 用种子数据填充了数据库,表中包含 Authors 表的外键。Notice that EF populated the database with the seed data, and the table contains the foreign key to the Authors table.