在本部分中,你將在EF上使用Code First Migration來用測試數(shù)據(jù)建立數(shù)據(jù)庫。
在Tools目錄下選擇Library Package Manager,然后選擇Package Manager Console。在包管理控制臺窗口,輸入以下命令:
Enable-Migrations
這條命令會添加一個名為Migrations的文件夾到你的項目,并添加一個名為Configuration.cs的代碼文件到Migrations文件夾。
如果在BookService中出現(xiàn)多種上下文類型,請輸入”Enable-Migrations –ContextTypeName BookService.Models.BookServiceContext”,具體請看下圖?!g者注。
打開Configuration.cs文件。添加以下using語句。
using BookService.Models;
然后添加以下代碼到Configuration.Seed方法:
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" }
);
}
在Package Manager Console窗口,鍵入以下命令:
Add-Migration Initial
Update-Database
第一條命令生成用于創(chuàng)建數(shù)據(jù)庫的代碼,第二條命令執(zhí)行那些代碼。數(shù)據(jù)庫使用LocalDB并創(chuàng)建于本地。
按F5在debug模式下運行應(yīng)用程序。Visual Studio啟動IIS Express并運行你的web應(yīng)用。Visual Studio會啟動一個瀏覽器并打開app的主頁。
當Visual Studio運行了這個web項目,它會給定一個端口號。在下圖中,端口號是50524。當你運行應(yīng)用程序的時候,你可能會看到不同的端口號。
主頁使用ASP.NET MVC來實現(xiàn)。在頁面頂部有一個寫著“API”的鏈接。該鏈接會帶你去一個自動生成的關(guān)于Web API的幫助頁面。(想了解這個幫助頁面如何生成的,以及你怎樣添加你自己的文檔進該頁面,查看Creating Help Pages for ASP.NET Web API(http://www.asp.net/web-api/overview/creating-web-apis/creating-api-help-pages)。)你可以點擊幫助頁面的鏈接以查看API的詳細信息,包括請求和相應(yīng)的格式。
該API支持在數(shù)據(jù)庫上執(zhí)行CRUD操作。下表是關(guān)于API的總結(jié)。
| 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. |
當你執(zhí)行了Update-Database命令,EF會創(chuàng)建數(shù)據(jù)庫并調(diào)用Seed方法。當你在本地執(zhí)行了應(yīng)用程序后,EF會使用LocalDB。你可以在Visual Studio中查看數(shù)據(jù)庫。在View目錄下,選擇SQL Server Object Explorer。
在Connect to Server對話框中,在Server Name編輯框,鍵入“(localdb)\v11.0”。保留Authentication選項為”Windows Authentication”。點擊Connect。
Visual Studio會連接到LocalDB并在SQL Server Object Explorer窗口顯示已經(jīng)存在的數(shù)據(jù)庫。你可以展開該節(jié)點查看EF創(chuàng)建的表。
為了看到數(shù)據(jù),右擊一個表并選擇View Data。
下面的截圖顯示了Books表的結(jié)果。注意EF通過seed數(shù)據(jù)聚集了數(shù)據(jù)庫,并且該表包含了指向Authors表的外鍵。