LoginSignup
3
2

More than 5 years have passed since last update.

[ASP.NET][Entity Framework] ASP.NET Core で Code First のマイグレーション自動適用

Posted at

Entity Framework Core で add されたマイグレーションは以下のコマンドでデータベースに手動適用できます。

[パッケージマネージャーコンソール]

Update-Database -Context FooContext

[CLI コマンド]

dotnet ef database update --context FooContext

ASP.NET Core でアプリケーション起動時にマイグレーションを自動適用させるためには、Program.Main メソッドに次のように記述します。

public static void Main(string[] args)
{
    var host = CreateWebHostBuilder(args).Build(); // ASP.NET Core 2.1~ の場合

    using (var scope = host.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
        try
        {
            var context = services.GetRequiredService<FooContext>();

            // 自動マイグレーション適用
            context.Database.Migrate();

            // 初期データ生成
            // ※Data フォルダ内にカスタムクラスを作成してデータ生成コードを記述しておく。
            DbInitializer.Initialize(context);
        }
        catch (Exception ex)
        {
            var logger = services.GetRequiredService<ILogger<Program>>();
            logger.LogError(ex, "データベース初期構成中にエラーが発生しました。");
        }
    }

    host.Run();
}

※Startup.Configure に記述すると Add-Migration で実行されてしまいます。(ASP.NET Core 2.0 で確認)

3
2
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
3
2