LoginSignup
0
1

More than 3 years have passed since last update.

初めてのマイグレーション

Last updated at Posted at 2020-11-06

マイグレーションとは

DBに保存されているデータを保持したまま、テーブルの作成やカラムの変更などを行うためのもの

マイグレーションのやり方(初回)

Entity Frameworkを使ったマイグレーションの方法をメモする

1.Entity Frameworkのインストール

  1. 「ツール」>「Nugetパッケージマネージャー」>「ソリューションのNugetパッケージの管理」
  2. 参照タブの検索欄で「EntityFramework」を入力し、「EntityFramework」を選択
  3. インストールしたいプロジェクトにチェックを付けてインストールをクリック

2.テーブルの作成

Person.cs
public class Product
{
    public int PersonId { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

3.Contextクラスの作成

MemberContext.cs
class MemberContext : DbContext
{
    public DbSet<Person> Persons { get; set; }
}

4.マイグレーションの準備

「表示」>「その他のウィンドウ」>「パッケージマネージャーコンソール」
コンソール画面を開き、以下のコマンドを入力

PM> Enable-Migrations

「Migrations」フォルダが作成されることを確認する

5.テーブルの新規作成

パッケージマネージャーコンソールに以下のコマンドを入力

PM> Add-Migration CreatePersons

「Migrations」フォルダの中にファイルが作成されていることを確認
※「202011060546053_CreatePersons」のような「年月日+UTC_入力したファイル名」というファイル名が作成されている

5.テーブルの更新

パッケージマネージャーコンソールに以下のコマンドを入力

PM> Update-Database

無事コマンド発行が成功すると、DBにPersonsテーブルが生成される

マイグレーションのやり方(二回目以降)

既に作成したDBに対して、変更を加えるための方法をメモする

1.テーブルの修正

「Person」テーブルに「Birthday」を追加する

Person.cs
public class Product
{
    public int PersonId{ get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public DateTime Birthday { get; set; }
}

2.更新用のマイグレーションファイルを作成する

パッケージマネージャーコンソールに以下のコマンドを入力

PM> Add-Migration ChangePersons_Birthday

3.テーブルの更新

パッケージマネージャーコンソールに以下のコマンドを入力

PM> Update-Database

無事コマンド発行が成功すると、Personsテーブルに「Birthday」が追加される

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1