Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 41 ยท Migrations

Applying Migrations: Update, Scripts and Bundles

Learn the safe ways to apply EF Core migrations - database update, Migrate at startup, idempotent SQL scripts and migration bundles - and which one to choose for production.

Creating a migration is easy; applying it safely is where teams get hurt. On your laptop dotnet ef database update is perfect. In production, running an unreviewed tool against a live database with your application's credentials is risky. EF Core offers four ways to apply migrations, and this lesson helps you choose.

The real tool cannot run on this site, so commands are read-only. Runnable stand-ins show idempotent scripts and ordered application.

1. dotnet ef database update

TEXT
dotnet ef database update                 # apply everything pending
dotnet ef database update AddDescription  # go to a specific migration (forward or back)
dotnet ef database update 0               # revert all migrations
dotnet ef database update --connection "Data Source=test.db"

Great for development and for throwaway environments. It needs the .NET SDK and your source code, which a production server normally does not have.

2. context.Database.Migrate() at startup

C#
using (var scope = app.Services.CreateScope())
{
    var db = scope.ServiceProvider.GetRequiredService<ShopContext>();
    await db.Database.MigrateAsync();
}

MigrateAsync applies pending migrations when the app starts. It is convenient for small apps and demos, but think before using it in production:

  • With several app instances starting together, two of them may try to migrate at the same time (EF Core 9+ takes a lock, but long migrations still delay startup).
  • The app's runtime login needs permission to alter the schema, which is more power than it should have.
  • A failed migration crashes the app on boot.

Use it for local development, tests and single-instance hobby projects.

3. SQL scripts

TEXT
dotnet ef migrations script                       # all migrations, from empty
dotnet ef migrations script AddDescription        # from empty to one migration
dotnet ef migrations script InitialCreate AddIndex   # between two migrations
dotnet ef migrations script --idempotent -o deploy.sql

The idempotent script checks __EFMigrationsHistory for each step and only runs what is missing, so it is safe to run against a database in any state:

SQL
IF NOT EXISTS (SELECT 1 FROM [__EFMigrationsHistory] WHERE [MigrationId] = N'20260110_AddDescription')
BEGIN
    ALTER TABLE [Products] ADD [Description] nvarchar(max) NULL;
    INSERT INTO [__EFMigrationsHistory] ([MigrationId], [ProductVersion])
    VALUES (N'20260110_AddDescription', N'10.0.0');
END;

A script can be reviewed by a DBA, stored with the release and run by your deployment pipeline with a privileged login. This is the safest default for production.

4. Migration bundles

TEXT
dotnet ef migrations bundle --self-contained -r linux-x64 -o efbundle
./efbundle --connection "Server=prod;Database=Shop;..."

A bundle is a single executable that contains all migrations and the EF Core runtime. It needs neither the SDK nor your source. You build it in CI, ship it with the release and run it as a deployment step, passing the connection string. It returns a non-zero exit code on failure, which pipelines understand.

Method Needs SDK Reviewable Best for
database update yes no local development
Migrate() at startup no no demos, tests, small apps
SQL script no yes production with DBA review
Bundle no partly automated production pipelines

Four ways to apply

database update Local development
Migrate() Startup, small apps
SQL script Reviewed releases
Bundle One executable

Pick by environment

1 / 2

Safe changes in production

Some changes are cheap, others lock tables or lose data:

  • Adding a nullable column is quick and compatible with the old app version.
  • Adding a NOT NULL column needs a default, or you split it: add nullable, backfill, then make it required in a later migration.
  • Renaming or dropping breaks the version of the app still running. Use expand and contract: add the new column, deploy code that writes both, backfill, switch reads, then drop the old column in a later release.
  • Big index builds can block writes on some databases; use the provider's online option (.IsCreatedOnline() on SQL Server).

Rolling back

dotnet ef database update PreviousMigration runs the Down methods. Dropped data is gone for good, so a rollback is not a substitute for a backup. In practice teams roll forward with a new corrective migration and keep backups for disasters.

Stand-in: an idempotent runner

This stand-in is not EF Core. It applies migrations in order, skips applied ones, stops at the first failure and records history only for steps that succeed. Run it and notice that the second run skips what already succeeded and retries only the failed step.

C# Stand-in: apply pending migrations safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Real providers wrap each migration in a transaction where the database supports transactional DDL (SQLite and PostgreSQL do, MySQL does not), so a failed step leaves no half-applied change.

Stand-in: generating an idempotent script

C# Stand-in: a guarded script

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which method is the safest default for production deployments with DBA review?

    A script can be reviewed, versioned and run with a privileged login. Idempotent means it is safe in any database state.
  2. 2. What does a migration bundle contain?

    A bundle is a self-contained executable you run as a deployment step with a connection string.
  3. 3. How do you rename a column with no downtime when old and new app versions overlap?

    A direct rename breaks the still-running old version. Expand and contract spreads the change over several releases.
  4. 4. Why is a Down migration not a safe backup strategy?

    Reverting a drop recreates the structure but not the data. Keep real backups and roll forward.

Summary

  • database update for development, Migrate() for demos and tests, SQL scripts or bundles for production.
  • Idempotent scripts check the history table, so they are safe to re-run.
  • Use expand and contract for breaking changes, and back up before risky migrations.
  • Prefer rolling forward with a new migration over Down.

Next: Seeding Data and Custom Migration SQL