Code First Migrations を使用してデータベースをシード処理する

完成したプロジェクトをダウンロードする

このセクションでは、EF の Code First Migrations を使用して、テスト データをデータベースにシード処理します。

[ツール] メニューで、[NuGet パッケージ マネージャー] を選択し、[パッケージ マネージャー コンソール] を選択します。 [パッケージ マネージャー コンソール] ウィンドウで、次のコマンドを入力します。

Enable-Migrations

このコマンドは、Migrations という名前のフォルダーをプロジェクトに追加し、Migrations フォルダーに Configuration.cs という名前のコード ファイルを追加します。

Screenshot of the Solution Explorer showing the folder hierarchy with the Configuration dot c s file highlighted in blue.

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" }
        );
}

[パッケージ マネージャー コンソール] ウィンドウで、次のコマンドを入力します。

Add-Migration Initial
Update-Database

最初のコマンドはデータベースを作成するコードを生成し、2 番目のコマンドはそのコードを実行します。 データベースは LocalDB を使用してローカルに作成されます。

Screenshot of the Package Manager Console window with the Enable Migrations, Add Migration Initial, and Update Database lines circled in red.

API の探索 (省略可能)

F5 キーを押してデバッグ モードでアプリケーションを実行します。 Visual Studio で IIS Express が開始され、Web アプリが実行されます。 その後、Visual Studio によってブラウザーが起動され、アプリのホーム ページが開きます。

Visual Studio が Web プロジェクトを実行すると、ポート番号が割り当てられます。 次の画像では、ポート番号は 50524 です。 アプリケーションを実行する際には、別のポート番号が表示されます。

Screenshot of the application window launched from Visual Studio in debug mode with the A P I link circled in red and highlighted with a red arrow.

ホーム ページは、ASP.NET MVC を使用して実装されます。 ページの上部には、"API" というリンクがあります。 このリンクをクリックすると、Web API の自動生成されたヘルプ ページが表示されます。 (このヘルプ ページの生成方法と、独自のドキュメントをページに追加する方法については、「ASP.NET Web API のヘルプ ページの作成」を参照してください)。ヘルプ ページのリンクをクリックすると、要求と応答の形式など、API に関する詳細を表示できます。

Screenshot of the auto-generated help page showing a list of links to documentation for API features.

この API により、データベースに対する CRUD 操作が有効になります。 API の概要を次に示します。

作者 説明
GET api/authors すべての作成者を取得します。
GET api/authors/{id} ID で作成者を取得します。
POST /api/authors 新しい作成者を作成します。
PUT /api/authors/{id} 既存の作成者を更新します。
DELETE /api/authors/{id} 作成者を削除します。
書籍 説明
GET /api/books すべての書籍を取得します。
GET /api/books/{id} ID で書籍を取得します。
POST /api/books 新しい書籍を作成します。
PUT /api/books/{id} 既存の書籍を更新します。
DELETE /api/books/{id} 書籍を削除します。

データベースの表示 (省略可能)

Update-Database コマンドを実行すると、EF によってデータベースが作成され、Seed メソッドが呼び出されました。 アプリケーションをローカルで実行すると、EF は LocalDB を使用します。 Visual Studio でデータベースを表示できます。 表示 メニューの SQL Server オブジェクト エクスプローラー を選択します。

Screenshot of the S Q L Server Object Explorer showing the S Q L Server item highlighted in blue and the Add S Q L Server item highlighted in yellow.

[サーバーへの接続] ダイアログボックスの [サーバー名] 編集ボックスに、「(localdb)\v11.0」と入力します。 [認証] オプションは [Windows 認証] のままにします。 [Connect] をクリックします。

Screenshot of the Connect to Server dialog showing the text local d b v 11 dot 0 in the Server name field and highlighted in blue.

Visual Studio は LocalDB に接続し、SQL Server オブジェクト エクスプローラー ウィンドウに既存のデータベースを表示します。 ノードを展開して、EF によって作成されたテーブルを表示できます。

Screenshot of the S Q L Server Object Explorer showing the folder hierarchy with the Book Service Context item highlighted in blue.

データを表示するには、テーブルを右クリックし、[データの表示] を選択します。

Screenshot of the S Q L Server Object Explorer showing the d b o dot Books item highlighted in blue and the View Data item highlighted in yellow.

次のスクリーンショットは、Books テーブルの結果を示しています。 EF によってシード データがデータベースに設定され、テーブルに Authors テーブルの外部キーが含まれていることに注目してください。

Screenshot of the Books table showing the database populated with seed data and the table containing the foreign key.