Skip to main content

Lesson 3 of 8

Migrations - Code-First Database Management

EF Core migrations track schema changes in code. Each migration is a versioned C# class that applies (Up) or reverts (Down) schema changes. In production: migrations run via CI/CD pipeline, never manually. In containerized environments: run migrations at app startup in a separate init container.

20 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Migration Workflow & Production Strategy

Migration Workflow & Production Strategy
# ━━ Creating migrations ━━
# Note: always run from solution root, specifying projects
dotnet ef migrations add InitialSchema \
  --project src/MyApp.Infrastructure \
  --startup-project src/MyApp.Api \
  --context AppDbContext

# List all migrations and their applied status
dotnet ef migrations list --project src/MyApp.Infrastructure --startup-project src/MyApp.Api

# Apply migrations to database
dotnet ef database update --project src/MyApp.Infrastructure --startup-project src/MyApp.Api

# Roll back to specific migration
dotnet ef database update PreviousMigrationName --project src/MyApp.Infrastructure --startup-project src/MyApp.Api
# (removes the last migration's changes)

# Remove the last UNAPPLIED migration (revert scaffolded code, not DB)
dotnet ef migrations remove --project src/MyApp.Infrastructure --startup-project src/MyApp.Api

# Generate SQL script for production (review BEFORE applying to prod DB)
dotnet ef migrations script --idempotent --output ./migrations.sql

// ━━ Apply migrations at startup (for dev/staging) ━━
// Program.cs:
if (app.Environment.IsDevelopment())
{
    using var scope = app.Services.CreateScope();
    var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
    await db.Database.MigrateAsync(); // apply pending migrations
}

// ━━ Production strategy: run migrations separately ━━
// In Docker: separate init container runs migrations before API starts
// In CI/CD: migration step after build, before deployment
// NEVER run migrations inside the running API pod (race condition with multiple instances)

// ━━ Data seeding within migrations ━━
// Infrastructure/Persistence/Migrations/20240101_InitialSchema.cs (generated):
// protected override void Up(MigrationBuilder migrationBuilder)
// {
//     migrationBuilder.CreateTable("Categories", ...);
//     // Seed reference data:
//     migrationBuilder.InsertData("Categories", new[] { "Id", "Name" },
//         new object[] { Guid.NewGuid(), "Electronics" });
// }

// ━━ HasData for model-based seeding ━━
// In entity configuration:
builder.HasData(
    new Category { Id = Guid.Parse("..."), Name = "Electronics", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow },
    new Category { Id = Guid.Parse("..."), Name = "Books", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }
);

Tip

Tip

Practice Migrations CodeFirst Database Management in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of Migrations CodeFirst Database Management from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Migrations CodeFirst Database Management is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done