Web API2 使用EF Code Migrations to Seed DB

时间:2021-12-18 08:23:58
console
Enable-Migrations

运行这个命令,添加一个文件夹Migrations,Configuration.cs在这文件夹中

Web API2 使用EF Code Migrations to Seed DB

打开 Configuration.cs file. 添加如下代码

C#
using BookService.Models;
C#
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" }
);
}

在包管理器控制台窗口中,键入以下命令:

console
Add-Migration Initial
Update-Database

第一个命令创建数据库的生成代码,和第二个命令执行该代码。在本地创建数据库,使用LocalDB。

Web API2 使用EF Code Migrations to Seed DB

探索 API (可选)

按F5在调试模式下运行应用程序。Visual Studio启动IIS Express和运行您的web应用程序。Visual Studio然后启动浏览器并打开应用程序的主页。

当Visual Studio运行一个web项目,它分配一个端口号。在下图中,端口号是50524。当你运行应用程序时,您将看到一个不同的端口号。

Web API2 使用EF Code Migrations to Seed DB

Web API2 使用EF Code Migrations to Seed DB

接口总汇

Authors  
GET api/authors Get all authors.
GET api/authors/{id} Get an author by ID.
POST /api/authors Create a new author.
PUT /api/authors/{id} Update an existing author.
DELETE /api/authors/{id} Delete an author.
Books  
GET /api/books Get all books.
GET /api/books/{id} Get a book by ID.
POST /api/books Create a new book.
PUT /api/books/{id} Update an existing book.
DELETE /api/books/{id} Delete a book.

查看 Database (可选)

当你运行update- database就命令,EF创建数据库并称为种子的方法。当你在本地运行应用程序,使用LocalDB EF。您可以查看数据库在Visual Studio。从视图菜单中,选择SQL Server对象资源管理器。

Web API2 使用EF Code Migrations to Seed DB

In the Connect to Server dialog, in the Server Name edit box, type "(localdb)\v11.0". Leave the Authentication option as "Windows Authentication". Click Connect.

Web API2 使用EF Code Migrations to Seed DB

Visual Studio连接LocalDB,显示现有数据库SQL Server对象资源管理器窗口中。您可以扩展节点EF创建的表。

Web API2 使用EF Code Migrations to Seed DB

To view the data, right-click a table and select View Data.

Web API2 使用EF Code Migrations to Seed DB+

下面的屏幕截图显示了书的结果表。注意,EF与种子填充数据库数据,和表包含作者表的外键。

Web API2 使用EF Code Migrations to Seed DB