EntityFramework(CodeFirst)でマイグレーション機能を使う |
・VisualStudio 2010 Express C#
(Web Developer 2010 Express)
・EntityFramework 6.0.2
・SQLServer2010 Express
「パッケージマネージコンソール」を使って
自動マイグレーションをやってみます。
今回はEntityクラスが最新情報とし、
その情報をDBに反映する運用を想定しています。
また、コードの例として下記の記事のクラス
「Parent」「Child」「DataContext」を使用します。
EntityFramework(CodeFirst)でJoinを試してみる
http://kazenetu.exblog.jp/19246594/
1.マイグレーション機能を有効にする(初回のみ)
パッケージマネージコンソールで下記のコマンドを入力します。
PM> Enable-Migrations
コマンドの発行結果は下記のとおりです。
Checking if the context targets an existing database...
Code First Migrations enabled for project WcfServiceEFTest.
プロジェクトに「Migrations」フォルダが作成され、
その中に「Configuration.cs」も作成されます。
2.EntityクラスとDBの差分を抽出する
パッケージマネージコンソールで下記のコマンドを入力します。
PM> Add-Migration Test
※Testは作成されるファイル名の一部になります。
分かりやすい名前にすることをおすすめします。
コマンドの発行結果は下記のとおりです。
Scaffolding migration 'Test'.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration Test' again.
「Migrations」フォルダに下記の「日時_Test.cs」が作成されます。
public partial class Test : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Children",
c => new
{
ID = c.Int(nullable: false, identity: true),
Name = c.String(),
ParentID = c.Int(nullable: false),
})
.PrimaryKey(t => t.ID)
.ForeignKey("dbo.Parents", t => t.ParentID, cascadeDelete: true)
.Index(t => t.ParentID);
CreateTable(
"dbo.Parents",
c => new
{
ID = c.Int(nullable: false, identity: true),
Name = c.String(),
})
.PrimaryKey(t => t.ID);
}
public override void Down()
{
DropForeignKey("dbo.Children", "ParentID", "dbo.Parents");
DropIndex("dbo.Children", new[] { "ParentID" });
DropTable("dbo.Parents");
DropTable("dbo.Children");
}
}
3.2で作成したファイルをDBに反映する
パッケージマネージコンソールで下記のコマンドを入力します。
PM> update-database
コマンドの実行結果は下記のとおりです。
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying explicit migrations: [2で作成されたファイル名].
Applying explicit migration: 2で作成されたファイル名.
Running Seed method.
DB(SQLServer)にテーブルが作成されました。
次回からは2と3を繰り返します。
試しに「Child」クラスに「Name2」というプロパティを追加します。
public class Child
{
public int ID { get; set; }
public string Name { get; set; }
public string Name2 { get; set; }
[ForeignKey("Parent")]
public int ParentID { get; set; }
public virtual Parent Parent { get; set; }
}
パッケージマネージコンソールで
Add-MigrationとUpdateを実行します。
「Migrations」フォルダに作られたファイルは下記の通りです。
public partial class Test1 : DbMigration
{
public override void Up()
{
AddColumn("dbo.Children", "Name2", c => c.String());
}
public override void Down()
{
DropColumn("dbo.Children", "Name2");
}
}
DB(SQLServer)に「Children」テーブルに「Name2」カラムが追加されました。
パッケージマネージコンソールでマイグレーションを利用すると下記の利点があります。
・ソースコードに
「Database.SetInitializer(new DropCreateDatabaseAlways());」
などのDB反映用コード記述が不要になる
・DropCreateせずカラム追加になるため、既存データが消失しない
注意点は下記のとおりです。
・DBによっては、大文字・小文字を変更しても反映されない
例)Name2→NAME2
※SQLServerで確認
・既存カラムを削除(プロパティを削除)した場合、既存データも消失する。
※Name2→Valueへの名称変更も同様
参考になれば幸いです。
よかったらクリックしてください。
にほんブログ村