Lesson 01 of 4 · 27 min read · Updated

EF Core Migrations the Right Way: Migration Bundles in CI/CD

Most EF Core tutorials end with the same three lines in Program.cs: create a scope, resolve the DbContext, call Database.MigrateAsync(). It works on the first day, and that is the problem. From then on every application instance changes the database schema when it starts, with credentials that are allowed to create, alter and drop tables.

In this lesson we move schema changes out of the application and into the deployment pipeline with EF Core migration bundles: a versioned executable that contains your compiled migrations and runs as its own step, with its own database identity. We build a Minimal API with two DbContexts on PostgreSQL, create bundles for both, run them locally, in a container, as a Kubernetes Job and in GitHub Actions, and look at what bundles do not solve: dry runs, rollbacks and zero-downtime changes.

This lesson is based on Scott Galloway's article You're Probably Doing EF Migrations Wrong. Every command and every output below was run against the sample code in the repository.

Technical Requirements

  1. .NET 10 SDK and EF Core 10. The sample was tested with SDK 10.0.402, EF Core 10.0.14 and Npgsql 10.0.3.
  2. Docker for PostgreSQL 17, and optionally a local Kubernetes cluster (Docker Desktop, kind or minikube) for the Job example.
  3. A recent IDE: Visual Studio 2026, Rider, or VS Code with C# Dev Kit.
  4. The full source code is on GitHub: Fcakiroglu16/dotnetacademy, branch efcore-migration-bundles
git clone https://github.com/Fcakiroglu16/dotnetacademy.git
cd dotnetacademy
git switch efcore-migration-bundles
docker compose up -d --wait
dotnet tool restore

The repository contains:

  1. src/MigrationBundles.Data: two contexts, CatalogDbContext and AuditDbContext, with their migrations
  2. src/MigrationBundles.Api: a Minimal API on port 5080 that uses both contexts
  3. db/init.sql: the database roles, created when the PostgreSQL container starts for the first time
  4. deploy/: a migrator container image and Kubernetes manifests
  5. .github/workflows/migrations.yml: the CI/CD pipeline

Why MigrateAsync at Startup Hurts

MigrateAsync() applies every pending migration and creates the database if it does not exist. Calling it at startup is simple, but it ties two different jobs together:

  1. Startup depends on the schema change. If the database is down or a migration fails, the application does not start. A failed migration becomes an outage.
  2. The application needs DDL permissions. The identity that serves HTTP requests must be allowed to create and alter tables, and often to drop them. Ordinary queries need far less.
  3. Every replica migrates. With three pods, three processes race to change the schema. EF Core 9 added a migration lock, so they no longer corrupt each other, but the lock does not stop old pods from serving requests against a schema that just changed under them.
  4. Failures hide in application logs instead of failing a pipeline step where someone is watching.

Runtime migrations are fine for local development, prototypes, personal projects and docker-compose dev environments, where convenience matters more than control. They are a poor fit for multiple instances, sensitive or regulated data, and anything with real users.

The Sample: Two Contexts, Two Identities

The catalog context holds categories and products. Its model grew in three migrations: InitialCreate, AddProductSku (a nullable Sku column with a unique index) and AddProductStock (an int column with a default).

src/MigrationBundles.Data/Catalog/CatalogDbContext.cs

using Microsoft.EntityFrameworkCore;

namespace MigrationBundles.Data.Catalog;

public class CatalogDbContext(DbContextOptions<CatalogDbContext> options) : DbContext(options)
{
public DbSet<Category> Categories => Set<Category>();
public DbSet<Product> Products => Set<Product>();

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Category>(category =>
{
category.Property(c => c.Name).HasMaxLength(100);
category.HasIndex(c => c.Name).IsUnique();
});

modelBuilder.Entity<Product>(product =>
{
product.Property(p => p.Name).HasMaxLength(200);
product.Property(p => p.Price).HasPrecision(10, 2);
product.Property(p => p.Sku).HasMaxLength(32);
product.HasIndex(p => p.Sku).IsUnique();
product.Property(p => p.Stock).HasDefaultValue(0);
});
}
}

The audit context lives in its own PostgreSQL schema, audit, and keeps its own __EFMigrationsHistory table there, so the two contexts never see each other's migrations. Its options are built by a static Configure method, because both the API and a design-time factory (covered later) must produce the same model.

src/MigrationBundles.Data/Audit/AuditDbContext.cs

using Microsoft.EntityFrameworkCore;

namespace MigrationBundles.Data.Audit;

public class AuditDbContext(DbContextOptions<AuditDbContext> options) : DbContext(options)
{
public const string Schema = "audit";

public DbSet<AuditEntry> Entries => Set<AuditEntry>();

// Shared by the API and the design-time factory so both build the same model.
public static DbContextOptionsBuilder Configure(DbContextOptionsBuilder options, string? connectionString) =>
options.UseNpgsql(connectionString, npgsql => npgsql.MigrationsHistoryTable("__EFMigrationsHistory", Schema));

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema(Schema);

modelBuilder.Entity<AuditEntry>(entry =>
{
entry.ToTable("entries");
entry.Property(e => e.Action).HasMaxLength(50);
entry.Property(e => e.CreatedAt).HasDefaultValueSql("now()");
entry.HasIndex(e => e.CreatedAt);
});
}
}

The most important file in the sample is not C#. It creates two PostgreSQL roles: shop_migrator owns the schema, and shop_app may only read and write data. Default privileges make every table the migrator creates later usable, but not alterable, by the app.

db/init.sql

-- Two identities: the migrator owns the schema, the application only reads and writes data.
CREATE ROLE shop_migrator LOGIN PASSWORD 'migrator_pw';
CREATE ROLE shop_app LOGIN PASSWORD 'app_pw';

-- shop: production-like database, schema changes only come from the migration bundle.
CREATE DATABASE shop OWNER shop_migrator;
-- shop_dev: local development database, the API migrates it on startup.
CREATE DATABASE shop_dev OWNER shop_migrator;

\connect shop
ALTER SCHEMA public OWNER TO shop_migrator;
GRANT CONNECT ON DATABASE shop TO shop_app;
GRANT USAGE ON SCHEMA public TO shop_app;
-- Everything the migrator creates later is readable/writable by the app, but never alterable.
ALTER DEFAULT PRIVILEGES FOR ROLE shop_migrator GRANT USAGE ON SCHEMAS TO shop_app;
ALTER DEFAULT PRIVILEGES FOR ROLE shop_migrator GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO shop_app;
ALTER DEFAULT PRIVILEGES FOR ROLE shop_migrator GRANT USAGE, SELECT ON SEQUENCES TO shop_app;

\connect shop_dev
ALTER SCHEMA public OWNER TO shop_migrator;

shop is the production-like database whose schema only changes through bundles. shop_dev is for local development.

The Hybrid Approach: Migrate on Startup Only in Development

Keeping MigrateAsync() for local development is a reasonable trade-off. The API registers both contexts and migrates on startup only when the environment is Development and a setting asks for it:

src/MigrationBundles.Api/Program.cs

using Microsoft.EntityFrameworkCore;
using MigrationBundles.Data.Audit;
using MigrationBundles.Data.Catalog;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<CatalogDbContext>(options => options
.UseNpgsql(builder.Configuration.GetConnectionString("Catalog"))
.UseSeeding(CatalogSeed.Seed)
.UseAsyncSeeding(CatalogSeed.SeedAsync));

builder.Services.AddDbContext<AuditDbContext>(options =>
AuditDbContext.Configure(options, builder.Configuration["Audit:ConnectionString"]));

var app = builder.Build();

// Hybrid approach: migrate on startup only for local development.
// Every other environment gets its schema from the migration bundle in CI/CD.
if (app.Environment.IsDevelopment() && app.Configuration.GetValue<bool>("Database:MigrateOnStartup"))
{
using var scope = app.Services.CreateScope();
await scope.ServiceProvider.GetRequiredService<CatalogDbContext>().Database.MigrateAsync();
await scope.ServiceProvider.GetRequiredService<AuditDbContext>().Database.MigrateAsync();
}

appsettings.Development.json points both contexts to shop_dev with the migrator identity and sets Database:MigrateOnStartup to true. appsettings.json, used everywhere else, has no connection string at all. The real ones come from environment variables or secrets.

dotnet run --project src/MigrationBundles.Api
info: Microsoft.EntityFrameworkCore.Migrations[20402]
Applying migration '20261028101052_InitialCreate'.
info: Microsoft.EntityFrameworkCore.Migrations[20402]
Applying migration '20261028101116_AddProductSku'.
info: Microsoft.EntityFrameworkCore.Migrations[20402]
Applying migration '20261028101118_AddProductStock'.
info: Microsoft.EntityFrameworkCore.Migrations[20402]
Applying migration '20261028101053_InitialCreate'.

Design-time tools do not run this block. When dotnet ef uses the API as its startup project, it builds the host and stops at builder.Build(), so migrations are not applied just because you added one.

Pin the EF Tools

The CLI that builds bundles should be the same version as the EF packages. Install it as a local tool so that CI and every developer use the pinned version:

dotnet new tool-manifest
dotnet tool install dotnet-ef --version 10.0.14

dotnet-tools.json

{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "10.0.14",
"commands": [
"dotnet-ef"
],
"rollForward": false
}
}
}

With the .NET 10 SDK, dotnet new tool-manifest creates dotnet-tools.json in the current folder. Older SDKs created .config/dotnet-tools.json. Both locations work. After cloning, dotnet tool restore installs the pinned version. The startup project also needs Microsoft.EntityFrameworkCore.Design.

Creating a Migration Bundle

A migration bundle is a single executable that contains the compiled migrations and the code needed to apply them. Think of dotnet ef database update packaged as a deployment artifact: the target machine needs no source code, no SDK and no EF CLI.

export ASPNETCORE_ENVIRONMENT=Production

dotnet ef migrations bundle \
--project src/MigrationBundles.Data \
--startup-project src/MigrationBundles.Api \
--context CatalogDbContext \
--configuration Release \
--output artifacts/catalog-bundle --force
Build started...
Build succeeded.
Building bundle...
Done. Migrations Bundle: /Users/.../dotnetacademy/artifacts/catalog-bundle
Don't forget to copy appsettings.json alongside your bundle if you need it to apply migrations.

Selecting Production matters: it keeps the tool from loading development settings, and it proves that building a bundle needs no connection string. The build only compiles migrations. It never touches a database, so the build job in CI needs no database credentials.

The options you will use most:

OptionPurpose
--output, -oPath of the executable to create
--force, -fOverwrite an existing bundle
--project, --startup-project, --contextWhere the migrations live, which project provides configuration, which context to bundle
--configuration, --frameworkBuild configuration and target framework
--target-runtime, -rThe runtime the bundle will run on, for example linux-x64 or linux-arm64
--self-containedInclude the .NET runtime, so the target does not need it installed
--no-buildSkip the build when the output is already up to date

Without --self-contained, a bundle is framework-dependent and needs a compatible .NET runtime on the target. Self-contained does not mean cross-platform: a linux-x64 bundle runs only on x64 Linux. Build for the real target OS, architecture and libc (linux-musl-x64 for Alpine).

Running the Bundle

The bundle has its own small command line. It is not the same as dotnet ef:

./catalog-bundle --help
Entity Framework Core Migrations Bundle 10.0.14

Usage: efbundle [arguments] [options] [[--] <arg>...]]

Arguments:
<MIGRATION> The target migration. If '0', all migrations will be reverted. Defaults to the last migration.

Options:
--connection <CONNECTION> The connection string to the database. Defaults to the one specified in AddDbContext or OnConfiguring.
--version Show version information
-h|--help Show help information
-v|--verbose Show verbose output.
--no-color Don't colorize output.
--prefix-output Prefix output with level.

The application identity cannot migrate

First, run it the way a startup migration would run, as shop_app:

cd artifacts
cp ../src/MigrationBundles.Api/appsettings.json .
./catalog-bundle --no-color \
--connection "Host=localhost;Port=5433;Database=shop;Username=shop_app;Password=app_pw"
echo $?
42501: permission denied for schema public
1

This is the separation we want. Even if someone adds MigrateAsync() to production code by mistake, the application cannot change the schema. The nonzero exit code is what stops a pipeline.

The migration identity can

MIG="Host=localhost;Port=5433;Database=shop;Username=shop_migrator;Password=migrator_pw"
./catalog-bundle --connection "$MIG" --no-color --prefix-output
error: Failed executing DbCommand (7ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
error: SELECT "MigrationId", "ProductVersion"
error: FROM "__EFMigrationsHistory"
error: ORDER BY "MigrationId";
info: Acquiring an exclusive lock for migration application. See https://aka.ms/efcore-docs-migrations-lock for more information if this takes too long.
info: Applying migration '20261028101052_InitialCreate'.
info: Applying migration '20261028101116_AddProductSku'.
info: Applying migration '20261028101118_AddProductStock'.
info: Done.

Two things in this output surprise people:

  1. The first error is expected. On a fresh database the history table does not exist yet. EF logs the failed SELECT, creates the table and continues. The exit code is 0.
  2. The migration lock. Since EF Core 9, migrations take an exclusive lock (on PostgreSQL, LOCK TABLE "__EFMigrationsHistory" IN ACCESS EXCLUSIVE MODE), so two bundles started at the same time do not apply the same migration twice.

Because the API is the startup project, the bundle also uses the API's logging configuration. Lines without a category come from the bundle. Lines with a category, such as Microsoft.EntityFrameworkCore.Migrations[20402], come from the application's console logger. The sample's appsettings.json lowers Microsoft.EntityFrameworkCore.Database.Command to Warning, so successful SQL statements are not logged. Don't lower the whole Microsoft.EntityFrameworkCore category, because that also hides the bundle's own "Applying migration" lines. This is why the build output reminds you to copy appsettings.json next to the bundle.

Run it again and nothing is applied:

./catalog-bundle --connection "$MIG" --no-color --prefix-output
info: Acquiring an exclusive lock for migration application. See https://aka.ms/efcore-docs-migrations-lock for more information if this takes too long.
info: No migrations were applied. The database is already up to date.
info: Done.

Overriding the connection

--connection overrides whatever the context would use. Without it, the bundle builds the context the same way the application does, so the connection comes from the app's configuration pipeline. With the default ASP.NET Core builder, environment variables override JSON files:

export ConnectionStrings__Catalog="$MIG"
./catalog-bundle

This only works because CatalogDbContext reads ConnectionStrings:Catalog. Environment variables are not a special bundle feature. They are configuration, and the key must match what your context or factory reads. AuditDbContext reads Audit:ConnectionString, so it needs Audit__ConnectionString.

Targeting a Migration and Reverting

The optional argument is the migration that should remain applied. It is positional. There is no --target-migration option.

./catalog-bundle 20261028101116_AddProductSku --connection "$MIG" --no-color

EF runs the Down() method of every newer migration. Here that is AddProductStock:

src/MigrationBundles.Data/Migrations/Catalog/20261028101118_AddProductStock.cs

using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace MigrationBundles.Data.Migrations.Catalog
{
/// <inheritdoc />
public partial class AddProductStock : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "Stock",
table: "Products",
type: "integer",
nullable: false,
defaultValue: 0);
}

/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Stock",
table: "Products");
}
}
}

0 reverts every migration. Only do that on a disposable database.

Reverting is not undo. In the test run, product 4 was created with "stock": 25. After reverting to AddProductSku and applying AddProductStock again, the column was back, with its default value:

{"id":4,"name":"EF Core Migrations Workshop","sku":"EF-MIG-01","price":29.90,"stock":0,"category":"Courses"}

DropColumn deletes the data, and AddColumn cannot bring it back. Review Down() as carefully as Up(). After a release, prefer a new corrective migration or a restore from a tested backup over running migrations backwards.

There Is No Dry Run: Use SQL Scripts

A bundle cannot show you what it would do. --verbose still applies migrations, and there is no --dry-run:

./catalog-bundle --dry-run
Specify --help for a list of available options and commands.
Unrecognized option '--dry-run'

To review the SQL, generate a script. A range script goes from one migration to another:

dotnet ef migrations script 20261028101116_AddProductSku 20261028101118_AddProductStock \
--project src/MigrationBundles.Data --startup-project src/MigrationBundles.Api \
--context CatalogDbContext --output artifacts/stock.sql
START TRANSACTION;
ALTER TABLE "Products" ADD "Stock" integer NOT NULL DEFAULT 0;

INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
VALUES ('20261028101118_AddProductStock', '10.0.14');

COMMIT;

Scripts also update the migration history. A range script assumes the database is exactly at the start migration. An idempotent script works from any state, because every migration is wrapped in a check:

dotnet ef migrations script --idempotent \
--project src/MigrationBundles.Data --startup-project src/MigrationBundles.Api \
--context CatalogDbContext --output artifacts/catalog-idempotent.sql
DO $EF$
BEGIN
IF NOT EXISTS(SELECT 1 FROM "__EFMigrationsHistory" WHERE "MigrationId" = '20261028101052_InitialCreate') THEN
CREATE TABLE "Categories" (
"Id" integer GENERATED BY DEFAULT AS IDENTITY,
"Name" character varying(100) NOT NULL,
CONSTRAINT "PK_Categories" PRIMARY KEY ("Id")
);
END IF;
END $EF$;

Idempotent scripts depend on the provider. SQLite cannot generate them.

When a DBA must approve the exact SQL, deploy the reviewed script itself, not a bundle. A bundle generates its SQL when it runs. Make the SQL client stop on the first error. For PostgreSQL:

psql --host=localhost --username=shop_migrator --dbname=shop_scripts \
--set=ON_ERROR_STOP=1 --file=catalog-idempotent.sql

Running the idempotent script twice against a fresh database succeeded both times. The second run only printed NOTICE: relation "__EFMigrationsHistory" already exists, skipping. A script that hits an error returns exit code 3 with ON_ERROR_STOP=1. For SQL Server, the equivalent is sqlcmd -b.

To see which migrations exist and which are pending:

dotnet ef migrations list \
--project src/MigrationBundles.Data --startup-project src/MigrationBundles.Api \
--context CatalogDbContext --connection "$EMPTY_DATABASE"
20261028101052_InitialCreate (Pending)
20261028101116_AddProductSku (Pending)
20261028101118_AddProductStock (Pending)

--no-connect lists migrations without contacting a database, but then it cannot tell you which are applied.

None of these test your data. A script can be syntactically perfect and still fail on a unique index because production has duplicate values. Test migrations against a fresh database and a restored, sanitized copy of a real one.

Catch Missing Migrations in CI

Someone changes the model and forgets dotnet ef migrations add. has-pending-model-changes, added in EF Core 8, compares the model with the snapshot and returns exit code 1 when they differ:

dotnet ef migrations has-pending-model-changes \
--project src/MigrationBundles.Data --startup-project src/MigrationBundles.Api \
--context CatalogDbContext
Changes have been made to the model since the last migration. Add a new migration.

Since EF Core 9 this is also enforced when migrations run. A bundle built from that model refused to run:

System.InvalidOperationException: An error was generated for warning 'Microsoft.EntityFrameworkCore.Migrations.PendingModelChangesWarning': The model for context 'CatalogDbContext' has pending changes. Add a new migration before updating the database.

Run the check in the build job so the pull request fails, not the deployment. The check compares the model with the snapshot. It does not tell you whether production has applied every migration, and it does not detect manual changes to the database. Don't suppress PendingModelChangesWarning to make it pass. A common cause is non-deterministic HasData values such as DateTime.Now or Guid.NewGuid().

Multiple Contexts and IDesignTimeDbContextFactory

Every context gets its own migrations folder and its own bundle:

dotnet ef migrations add InitialCreate \
--project src/MigrationBundles.Data --startup-project src/MigrationBundles.Data \
--context AuditDbContext --output-dir Migrations/Audit

Notice the startup project: the audit context does not need the API at all. EF tools have to create the context, and when a class implements IDesignTimeDbContextFactory<T>, they use it instead of the application's service provider. That includes bundles:

src/MigrationBundles.Data/Audit/AuditDbContextFactory.cs

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;

namespace MigrationBundles.Data.Audit;

// Used by dotnet ef and by the audit bundle instead of the API's startup code.
public class AuditDbContextFactory : IDesignTimeDbContextFactory<AuditDbContext>
{
public AuditDbContext CreateDbContext(string[] args)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true)
.AddEnvironmentVariables()
.Build();

// A bundle passes --connection on to the context afterwards, so the key is optional here.
var connectionString = configuration["Audit:ConnectionString"];

var options = new DbContextOptionsBuilder<AuditDbContext>();
AuditDbContext.Configure(options, connectionString);
return new AuditDbContext(options.Options);
}
}

A factory is useful when the context lives in a class library, when startup is complex or needs services that are not available at design time, or when you want full control over how tools create the context. Two rules:

  1. Build the same model as the application. Here both call AuditDbContext.Configure, so the history table is always in the audit schema.
  2. Keep production secrets out of it. The connection string is optional here, because the bundle receives it through --connection.
dotnet ef migrations bundle \
--project src/MigrationBundles.Data --startup-project src/MigrationBundles.Data \
--context AuditDbContext --configuration Release \
--output artifacts/audit-bundle --force

./audit-bundle --connection "$MIG" --no-color --prefix-output
info: Acquiring an exclusive lock for migration application. See https://aka.ms/efcore-docs-migrations-lock for more information if this takes too long.
info: Applying migration '20261028101053_InitialCreate'.
info: Done.

Both histories are now independent:

MigrationId
--------------------------------
20261028101052_InitialCreate
20261028101116_AddProductSku
20261028101118_AddProductStock
(3 rows)

MigrationId
------------------------------
20261028101053_InitialCreate
(1 row)

Seeding with UseSeeding and UseAsyncSeeding

EF Core 9 added UseSeeding and UseAsyncSeeding for seed data that HasData cannot express well. They run after migrations are applied, inside the migration lock. The sample registers both in AddDbContext:

src/MigrationBundles.Data/Catalog/CatalogSeed.cs

using Microsoft.EntityFrameworkCore;

namespace MigrationBundles.Data.Catalog;

// Runs from UseSeeding/UseAsyncSeeding after every Migrate call, even when no migration
// was pending, so it must check for existing data before inserting.
public static class CatalogSeed
{
public static void Seed(DbContext context, bool _)
{
var categories = context.Set<Category>();
if (categories.Any())
{
return;
}

categories.AddRange(CreateCategories());
context.SaveChanges();
}

public static async Task SeedAsync(DbContext context, bool _, CancellationToken cancellationToken)
{
var categories = context.Set<Category>();
if (await categories.AnyAsync(cancellationToken))
{
return;
}

categories.AddRange(CreateCategories());
await context.SaveChangesAsync(cancellationToken);
}

private static Category[] CreateCategories() =>
[
new()
{
Name = "Books",
Products =
[
new() { Name = "Entity Framework Core in Action", Price = 49.90m },
new() { Name = "C# 14 and .NET 10", Price = 54.50m },
],
},
new()
{
Name = "Courses",
Products = [new() { Name = "Kubernetes for .NET Developers", Price = 19.99m }],
},
];
}

Implement both. Migrate(), which tools and bundles use, calls the synchronous one, and MigrateAsync() calls the asynchronous one. Seeding also runs when no migration was pending. A quick test with counting delegates printed:

Migrate(): sync
MigrateAsync() with nothing pending: async

With SQL logging enabled, a bundle run that applied nothing still ended with the seeding query:

SELECT EXISTS (
SELECT 1
FROM "Categories" AS c)

That is why both methods check for data first.

SQL scripts do not contain seeding code. The database migrated with the idempotent script had all three migrations and zero categories.

A Schema Readiness Check in the API

When migrations run in a separate step, the application should notice if that step did not happen. The sample exposes a readiness endpoint that asks EF for pending migrations:

src/MigrationBundles.Api/Program.cs

// Readiness check: the app refuses traffic until the bundle has brought the schema up to date.
app.MapGet("/health/schema", async (CatalogDbContext catalog, AuditDbContext audit) =>
{
var pending = new Dictionary<string, IEnumerable<string>>
{
["catalog"] = await catalog.Database.GetPendingMigrationsAsync(),
["audit"] = await audit.Database.GetPendingMigrationsAsync(),
};

return pending.Values.Any(p => p.Any())
? Results.Json(pending, statusCode: StatusCodes.Status503ServiceUnavailable)
: Results.Ok(pending);
});

Run the API as shop_app, with no development settings:

APP="Host=localhost;Port=5433;Database=shop;Username=shop_app;Password=app_pw"
ConnectionStrings__Catalog="$APP" Audit__ConnectionString="$APP" \
ASPNETCORE_ENVIRONMENT=Production ASPNETCORE_URLS=http://localhost:5080 \
dotnet run --no-launch-profile --project src/MigrationBundles.Api
curl localhost:5080/health/schema
{"catalog":[],"audit":[]}

curl -X POST localhost:5080/products -H 'Content-Type: application/json' \
-d '{"name":"EF Core Migrations Workshop","sku":"EF-MIG-01","price":29.90,"stock":25,"categoryId":2}'
4

Now revert AddProductStock while the API is running, to simulate new code deployed before its migration:

curl -w ' %{http_code}' localhost:5080/health/schema
{"catalog":["20261028101118_AddProductStock"],"audit":[]} 503

curl -w ' %{http_code}' localhost:5080/products
500

The query fails with errorMissingColumn, but the readiness check said so first. As a Kubernetes readiness probe, this endpoint keeps new pods out of the load balancer until the bundle has run. Reading the history table only needs SELECT, which shop_app has.

The Pipeline: GitHub Actions

The pipeline has two jobs with different trust levels:

  1. build has no database credentials. It checks for model changes, generates idempotent SQL for review, builds self-contained linux-x64 bundles and uploads them as one artifact.
  2. migrate downloads that artifact and runs it. It does not build anything and needs no SDK. The same artifact moves through test, staging and production.

.github/workflows/migrations.yml

name: EF Core migration bundles

on:
push:
branches: [efcore-migration-bundles]
pull_request:
branches: [efcore-migration-bundles]
workflow_dispatch:

jobs:
build:
# Build job: no database credentials at all.
runs-on: ubuntu-latest
env:
ASPNETCORE_ENVIRONMENT: Production
DOTNET_ENVIRONMENT: Production
steps:
- uses: actions/checkout@v7

- uses: actions/setup-dotnet@v6
with:
global-json-file: global.json

- name: Restore
run: |
dotnet tool restore
dotnet restore

- name: Fail if the model has changes without a migration
run: |
dotnet ef migrations has-pending-model-changes \
--project src/MigrationBundles.Data --startup-project src/MigrationBundles.Api --context CatalogDbContext
dotnet ef migrations has-pending-model-changes \
--project src/MigrationBundles.Data --startup-project src/MigrationBundles.Data --context AuditDbContext

- name: Generate idempotent SQL for review
run: |
dotnet ef migrations script --idempotent \
--project src/MigrationBundles.Data --startup-project src/MigrationBundles.Api --context CatalogDbContext \
--output out/catalog.sql
dotnet ef migrations script --idempotent \
--project src/MigrationBundles.Data --startup-project src/MigrationBundles.Data --context AuditDbContext \
--output out/audit.sql

- name: Build Linux migration bundles
run: |
dotnet ef migrations bundle \
--project src/MigrationBundles.Data --startup-project src/MigrationBundles.Api --context CatalogDbContext \
--configuration Release --target-runtime linux-x64 --self-contained \
--output out/catalog-bundle
dotnet ef migrations bundle \
--project src/MigrationBundles.Data --startup-project src/MigrationBundles.Data --context AuditDbContext \
--configuration Release --target-runtime linux-x64 --self-contained \
--output out/audit-bundle
cp src/MigrationBundles.Api/appsettings.json out/

- uses: actions/upload-artifact@v7
with:
name: ef-migrations
path: out/

migrate:
# Deployment job: receives the tested artifact, never the source code or the SDK.
needs: build
runs-on: ubuntu-latest
# In a real pipeline: environment: production (with required reviewers),
# and the connection string comes from ${{ secrets.MIGRATION_CONNECTION_STRING }}.
concurrency:
group: shop-database-migrations
cancel-in-progress: false
services:
postgres:
image: postgres:17
env:
POSTGRES_PASSWORD: postgres
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U postgres"
--health-interval 2s
--health-retries 30
env:
ASPNETCORE_ENVIRONMENT: Production
DOTNET_ENVIRONMENT: Production
MIGRATION_CONNECTION_STRING: Host=localhost;Database=shop;Username=shop_migrator;Password=migrator_pw
APP_CONNECTION_STRING: Host=localhost;Database=shop;Username=shop_app;Password=app_pw
PGPASSWORD: postgres
steps:
# Only db/init.sql is checked out, to create the demo roles. A real deployment needs no source.
- uses: actions/checkout@v7
with:
sparse-checkout: db

- name: Create demo roles and databases
run: psql --host=localhost --username=postgres --set=ON_ERROR_STOP=1 --file=db/init.sql

- uses: actions/download-artifact@v8
with:
name: ef-migrations
path: bundle

- name: The application identity cannot change the schema
working-directory: bundle
run: |
chmod +x catalog-bundle audit-bundle
if ./catalog-bundle --connection "$APP_CONNECTION_STRING" --no-color > app-identity.log 2>&1; then
echo "::error::shop_app was able to run migrations"; exit 1
fi
grep -m1 "42501" app-identity.log

- name: Apply migrations
working-directory: bundle
run: |
./catalog-bundle --connection "$MIGRATION_CONNECTION_STRING" --no-color --prefix-output
./audit-bundle --connection "$MIGRATION_CONNECTION_STRING" --no-color --prefix-output

- name: Run again, nothing should be applied
working-directory: bundle
run: ./catalog-bundle --connection "$MIGRATION_CONNECTION_STRING" --no-color --prefix-output | grep "No migrations were applied"

- name: Verify the schema
run: |
psql --host=localhost --username=postgres --dbname=shop --set=ON_ERROR_STOP=1 \
-c 'SELECT "MigrationId" FROM "__EFMigrationsHistory"' \
-c 'SELECT "MigrationId" FROM audit."__EFMigrationsHistory"' \
-c 'SELECT "Name", "Stock" FROM "Products"'

In the sample, the migrate job uses a PostgreSQL service container, so the pipeline runs on every push without a real server. It proves the same things as the local run: shop_app gets 42501, shop_migrator applies every migration, and the second run applies nothing. In a real pipeline, add environment: production with required reviewers and take the connection string from an environment secret. The concurrency group makes sure two deployments never migrate the same database at the same time.

Bundle generation takes several seconds and self-contained bundles are large (about 140 MB for linux-arm64 here). Build them in CI, not on every local build.

Packaging the Bundle as a Container Image

Container platforms want an image, not a file. The migrator image builds both bundles in the SDK image and copies them into runtime-deps, the smallest .NET base image. It contains no runtime and no SDK:

deploy/Dockerfile.migrator

# Builds a self-contained migration bundle and ships it in a tiny image without the .NET runtime or SDK.
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
ARG TARGETARCH
WORKDIR /src

COPY global.json dotnet-tools.json MigrationBundles.slnx ./
COPY src/MigrationBundles.Data/MigrationBundles.Data.csproj src/MigrationBundles.Data/
COPY src/MigrationBundles.Api/MigrationBundles.Api.csproj src/MigrationBundles.Api/
RUN dotnet tool restore && dotnet restore src/MigrationBundles.Api -a $TARGETARCH

COPY src/ src/
ENV ASPNETCORE_ENVIRONMENT=Production DOTNET_ENVIRONMENT=Production
RUN dotnet ef migrations bundle \
--project src/MigrationBundles.Data \
--startup-project src/MigrationBundles.Api \
--context CatalogDbContext \
--configuration Release \
--target-runtime linux-$([ "$TARGETARCH" = "arm64" ] && echo arm64 || echo x64) \
--self-contained \
--output /out/catalog-bundle \
&& dotnet ef migrations bundle \
--project src/MigrationBundles.Data \
--startup-project src/MigrationBundles.Data \
--context AuditDbContext \
--configuration Release \
--target-runtime linux-$([ "$TARGETARCH" = "arm64" ] && echo arm64 || echo x64) \
--self-contained \
--output /out/audit-bundle \
&& cp src/MigrationBundles.Api/appsettings.json /out/

FROM mcr.microsoft.com/dotnet/runtime-deps:10.0
# Self-contained still needs the OS libraries the provider loads; Npgsql probes for GSSAPI (Kerberos).
RUN apt-get update \
&& apt-get install -y --no-install-recommends libgssapi-krb5-2 \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /migrations
COPY --from=build /out/ ./
COPY deploy/migrate.sh ./
USER $APP_UID
ENTRYPOINT ["./migrate.sh"]

deploy/migrate.sh

#!/bin/sh
# Applies both contexts with the migration identity. Any nonzero exit fails the Job.
set -eu
./catalog-bundle --connection "$MIGRATION_CONNECTION_STRING" --no-color --prefix-output
./audit-bundle --connection "$MIGRATION_CONNECTION_STRING" --no-color --prefix-output

The first version of this image did not install libgssapi-krb5-2, and every run printed:

Cannot load library libgssapi_krb5.so.2
Error: libgssapi_krb5.so.2: cannot open shared object file: No such file or directory

Self-contained includes the .NET runtime, but not the operating system libraries that your database provider loads. Npgsql looks for GSSAPI for Kerberos authentication. The migrations still ran, but don't ship an image that prints errors on every run. GitHub's Ubuntu runners have the library installed, so this only shows up in minimal images.

docker build -f deploy/Dockerfile.migrator -t shop-migrator:1.0.0 .
docker run --rm --network migration-bundles_default \
-e MIGRATION_CONNECTION_STRING="Host=postgres;Database=shop_docker;Username=shop_migrator;Password=migrator_pw" \
shop-migrator:1.0.0

The image runs as the non-root app user (uid=1654) that .NET images provide.

Kubernetes: A Job, Not an Init Container

An init container is the obvious idea: the app container waits until the init container has migrated the database. But init containers run once per pod. With five replicas, every rollout runs five migration processes, and every pod restart runs another one. A Job runs once per release:

deploy/k8s/migration-job.yaml

# One Job per release: runs once per deployment, not once per pod like an init container would.
apiVersion: batch/v1
kind: Job
metadata:
name: shop-migrate-1-0-0
labels:
app: shop-migrator
release: "1.0.0"
spec:
backoffLimit: 0 # a failed migration needs a human, not blind retries
activeDeadlineSeconds: 600
ttlSecondsAfterFinished: 86400
template:
metadata:
labels:
app: shop-migrator
spec:
restartPolicy: Never
containers:
- name: migrate
image: shop-migrator:1.0.0
imagePullPolicy: IfNotPresent
env:
- name: MIGRATION_CONNECTION_STRING
valueFrom:
secretKeyRef:
name: shop-migrator-db # migration identity, not the app's credentials
key: connection-string

backoffLimit: 0 is deliberate. A failed migration may have done part of its work, and retrying it automatically rarely helps. The Job reads the migrator's connection string from its own secret. The application's pods never get it.

kubectl create namespace ef-bundles-demo
kubectl -n ef-bundles-demo create configmap postgres-init --from-file=init.sql=db/init.sql
kubectl -n ef-bundles-demo apply -f deploy/k8s/postgres.yaml
kubectl -n ef-bundles-demo rollout status deploy/postgres
kubectl -n ef-bundles-demo create secret generic shop-migrator-db \
--from-literal=connection-string="Host=postgres;Database=shop;Username=shop_migrator;Password=migrator_pw"
kubectl -n ef-bundles-demo apply -f deploy/k8s/migration-job.yaml
kubectl -n ef-bundles-demo wait --for=condition=complete job/shop-migrate-1-0-0

To see a failure, the same Job was started with the application's credentials:

NAME STATUS COMPLETIONS DURATION AGE
shop-migrate-1-0-0 Complete 1/1 5s 14s
shop-migrate-wrong-identity Failed 0/1 3s 3s
kubectl -n ef-bundles-demo logs job/shop-migrate-wrong-identity
info: Npgsql.PostgresException (0x80004005): 42501: permission denied for schema public

Your deployment tool must wait for the Job before it updates the application: a Helm pre-upgrade hook, an Argo CD sync wave, or simply kubectl wait in the pipeline. The /health/schema readiness probe is the safety net if that order is ever broken.

kubectl delete namespace ef-bundles-demo

Commit All Three Migration Files

Migrations work on your machine and fail in CI? Check that all generated files are committed:

  1. 20261028101118_AddProductStock.cs: the Up() and Down() code
  2. 20261028101118_AddProductStock.Designer.cs: the [Migration] attribute and the target model of that migration. Without it, EF does not find the migration.
  3. CatalogDbContextModelSnapshot.cs: the current model, one per context. A missing or stale snapshot produces wrong diffs for the next migration, and has-pending-model-changes fails.

Don't mix in EnsureCreated(). It creates the schema without migrations and without a history table. A later MigrateAsync() then tries to create tables that already exist:

PostgresException: 42P07: relation "Categories" already exists

Use EnsureCreated() only for throwaway databases, such as some test setups, that never use migrations.

Comparing the Options

ApproachBest forNeeds .NET on targetTracks applied migrationsDBA friendly
MigrateAsync() at startupLocal development, prototypesYes, inside the appYesNo
Migration bundleCI/CD pipelinesNo, if self-containedYesPartly
SQL scriptDBA-controlled environmentsNoYes, scripts write the history; --idempotent adds checksYes
DACPAC (SQL Server)SQL Server teams with database projectsNoNo, it compares schemas insteadYes

Migration tools such as FluentMigrator and DbUp work too. The difference is that EF bundles come directly from the EF model you already maintain.

Zero Downtime Is a Deployment Strategy

Bundles deliver schema changes in a controlled way. They do not make a breaking change safe while old code is still running. For that, split every breaking change into steps (expand and contract):

  1. Expand: add what the old code tolerates, such as a nullable column. AddProductSku is this kind of change.
  2. Deploy code that writes both the old and the new shape.
  3. Backfill existing rows and verify them.
  4. Switch reads and add constraints when code and data are ready.
  5. Contract: remove the old column in a later release, after every old instance is gone.

Measure lock times and table rewrites on a realistic copy of the data before you run these steps in production.

Summary

  1. MigrateAsync() at startup couples application startup to schema changes and gives the app DDL permissions. Keep it for local development, behind an environment check.
  2. A migration bundle is an executable with your compiled migrations. Build it in CI without database credentials, then run the same artifact in every environment.
  3. Give the bundle its own database identity. The application identity should fail with a permission error if it ever tries to migrate.
  4. The bundle's only argument is the migration that should remain applied. 0 reverts everything, and Down() cannot bring deleted data back.
  5. There is no dry run. Review dotnet ef migrations script output, use --idempotent for DBA-approved deployments, and test against a restored copy of real data.
  6. has-pending-model-changes catches forgotten migrations in the pull request. EF Core 9+ also refuses to apply migrations when the model is ahead of the snapshot.
  7. IDesignTimeDbContextFactory decides how tools and bundles create a context. Environment variables only work if the factory or context reads that key.
  8. UseSeeding and UseAsyncSeeding run on every migration run, even when nothing is pending, so make them idempotent. SQL scripts do not include them.
  9. In containers, self-contained bundles still need the native libraries your provider loads. In Kubernetes, run a Job once per release instead of an init container per pod.

Source code: github.com/Fcakiroglu16/dotnetacademy/tree/efcore-migration-bundles