console
Enable-Migrations

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

打开 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。

探索 API (可选)

当你运行应用程序时,您将看到一个不同的端口号。

接口总汇

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 (可选)

从视图菜单中,选择SQL Server对象资源管理器。

您可以扩展节点EF创建的表。

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

+

注意,EF与种子填充数据库数据,和表包含作者表的外键。

相关文章:

猜你喜欢
  • 2021-10-31
  • 2022-12-23
  • 2021-07-02
  • 2021-06-12
  • 2021-09-16
  • 2021-12-07
相关资源
相似解决方案