LESSON 10 OF 14

10. Managing Entity Framework Core Migrations in Containers

In this lesson, you will create EF Core migrations, apply them to a SQL Server container, run the CLI from an SDK container, and solve SQL Server readiness problems.

75 dk 58

Introduction

In the previous lessons, we connected the API and SQL Server containers through a Docker network and used a volume to persist database files. However, connectivity alone is not enough for a maintainable application. When entity classes change, the SQL Server schema must be updated in a controlled way. Entity Framework Core migrations provide the workflow for keeping the application model and database schema synchronized.

This lesson uses a project named CatalogApi. We will assume that it contains a Product entity and a CatalogDbContext class. You will create an initial migration, apply it to SQL Server, add a second migration after changing the model, and run EF Core CLI commands both on the host machine and inside a .NET SDK container.

Understanding Migrations

An EF Core migration describes the difference between the current model and the previous model snapshot. The dotnet ef migrations add command generates source files that describe schema changes. The dotnet ef database update command applies pending migrations to the target database.

Applied migrations are recorded in the SQL Server table named __EFMigrationsHistory. EF Core uses this table to determine which migrations have already been applied and runs only the missing ones. Migration files should be committed to source control because they represent the history of the database schema and are required when another developer, environment, or deployment process updates the database.

Required packages

The project file must reference the SQL Server provider and the EF Core design package. The versions should match the .NET and EF Core versions used by the project.

<ItemGroup>  <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.0" />  <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.0">    <PrivateAssets>all</PrivateAssets>    <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>  </PackageReference> </ItemGroup>

If the EF CLI is not installed on the development machine, install the matching tool version:

dotnet tool install --global dotnet-ef --version 8.0.0

Preparing the DbContext and Connection String

EF CLI commands must create the DbContext at design time. Therefore, the database configuration must be available both when the application runs and when the tooling runs. If the SQL Server service in Docker Compose is named sqlserver, containers must use sqlserver as the host name. Inside a container, localhost points to that same container, not to the SQL Server container.

builder.Services.AddDbContext<CatalogDbContext>(options =>    options.UseSqlServer(        builder.Configuration.GetConnectionString("DefaultConnection"))); var app = builder.Build();

For local development, a connection string may use the port published on the host:

{  "ConnectionStrings": {    "DefaultConnection": "Server=localhost,1433;Database=CatalogDb;User Id=sa;Password=Your_password123;TrustServerCertificate=True;"  } }

When the API or migration command runs inside the Compose network, use the service name instead:

Server=sqlserver,1433;Database=CatalogDb;User Id=sa;Password=Your_password123;TrustServerCertificate=True;

The password in these examples is for demonstration only. Do not commit database passwords to source control. Use environment variables, Docker secrets, a secret store, or CI/CD secret variables in real projects.

Creating the Initial Migration

The SQL Server container should be running before applying a migration. Creating a migration locally does not always require a live database connection, but EF tooling must still be able to construct the DbContext. From the project directory, run:

dotnet restore dotnet ef migrations add InitialCreate --project src/CatalogApi/CatalogApi.csproj

If the command succeeds, a Migrations directory is usually created. It contains the migration class, metadata, and model snapshot. Review these files to understand how EF Core represents tables, keys, columns, and indexes.

Migration files generally should not be edited manually. You should, however, review the generated code and any data-loss warnings. For example, removing a property and adding another property may generate a drop-and-add operation instead of a column rename, which can delete existing data.

Applying the Migration to SQL Server

Once SQL Server is accepting connections, the following command creates the database if necessary and applies all pending migrations:

dotnet ef database update --project src/CatalogApi/CatalogApi.csproj

To update the database only through a specific migration, provide its name:

dotnet ef database update InitialCreate --project src/CatalogApi/CatalogApi.csproj

You can verify the result through container logs and SQL Server:

docker compose logs sqlserver docker compose exec sqlserver /opt/mssql-tools18/bin/sqlcmd \  -S localhost -U sa -P "Your_password123" -C \  -Q "SELECT name FROM sys.databases;" docker compose exec sqlserver /opt/mssql-tools18/bin/sqlcmd \  -S localhost -U sa -P "Your_password123" -C \  -d CatalogDb -Q "SELECT * FROM __EFMigrationsHistory;"

The location of sqlcmd can vary between SQL Server image versions. If the path does not exist, inspect the image or use SQL Server Management Studio, Azure Data Studio, or another compatible SQL client.

Changing the Model and Creating a Second Migration

Now add a property to the Product entity:

public class Product {    public int Id { get; set; }    public string Name { get; set; } = string.Empty;    public decimal Price { get; set; }    public DateTime CreatedAtUtc { get; set; }    public bool IsActive { get; set; } = true; }

Create a new migration after changing the model:

dotnet ef migrations add AddProductStatus \  --project src/CatalogApi/CatalogApi.csproj

Inspect the generated migration. EF Core will typically add an SQL Server bit column for IsActive and provide a default value for existing rows. Apply it with:

dotnet ef database update \  --project src/CatalogApi/CatalogApi.csproj

The following command lists migrations known to the project:

dotnet ef migrations list \  --project src/CatalogApi/CatalogApi.csproj

Remember that generating a migration and applying a migration are separate operations. A migration can exist in source control without having been applied to a particular database.

Running EF CLI from an SDK Container

If you do not want to install the .NET SDK or dotnet-ef on the host machine, run the commands in a .NET SDK container. Mounting the source directory ensures that migration files generated inside the container remain on the host machine.

docker run --rm -it \  -v "${PWD}:/src" \  -w /src \  --network catalog_default \  mcr.microsoft.com/dotnet/sdk:8.0 \  bash

Adjust the volume syntax for Windows PowerShell or another shell. After entering the container, run:

dotnet restore dotnet tool install --global dotnet-ef --version 8.0.0 export PATH="$PATH:/root/.dotnet/tools" dotnet ef migrations add InitialCreate \  --project src/CatalogApi/CatalogApi.csproj dotnet ef database update \  --project src/CatalogApi/CatalogApi.csproj

When the SDK container is connected to the Compose network, the connection string must use sqlserver as the host. You can check the network name with docker network ls.

Handling SQL Server Readiness

A started container is not necessarily a ready SQL Server instance. During its first startup, SQL Server may initialize system databases and reject connections for several seconds. If an API or migration container starts immediately, you may see connection refused, login failed, or cannot open database errors.

Add a health check to the SQL Server service and make the migration service depend on the healthy state:

services:  sqlserver:    image: mcr.microsoft.com/mssql/server:2022-latest    environment:      ACCEPT_EULA: "Y"      MSSQL_SA_PASSWORD: "Your_password123"    ports:      - "1433:1433"    volumes:      - sqlserver-data:/var/opt/mssql    healthcheck:      test: ["CMD-SHELL", "/opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P \"$$MSSQL_SA_PASSWORD\" -C -Q \"SELECT 1\" || exit 1"]      interval: 10s      timeout: 5s      retries: 12      start_period: 20s  migrator:    image: mcr.microsoft.com/dotnet/sdk:8.0    working_dir: /src    volumes:      - .:/src    environment:      ConnectionStrings__DefaultConnection: "Server=sqlserver,1433;Database=CatalogDb;User Id=sa;Password=Your_password123;TrustServerCertificate=True;"    depends_on:      sqlserver:        condition: service_healthy    command: >      bash -c "dotnet restore &&      dotnet tool install --global dotnet-ef --version 8.0.0 &&      export PATH=\"$$PATH:/root/.dotnet/tools\" &&      dotnet ef database update --project src/CatalogApi/CatalogApi.csproj" volumes:  sqlserver-data:

Run the one-shot migration service with:

docker compose run --rm migrator

The health check prevents the migrator from starting before SQL Server is ready. If the migration command itself fails, inspect the logs rather than blindly restarting it. A failed migration may require reviewing the connection string, generated SQL, or the database state.

Common Mistakes

  • Using the wrong host name: From a container, use the Compose service name, sqlserver in this example, instead of localhost.
  • Confusing host and container ports: From the host use localhost,1433; from the Docker network use sqlserver,1433.
  • Missing the design package: For Unable to create an object of type DbContext, check the design package, constructor, startup project, and configuration.
  • Reusing an old volume: An existing SQL Server volume may contain a previous password or database state. In development, docker compose down -v removes the volume, but it also deletes the data.
  • Mixing EnsureCreated and migrations: EnsureCreated bypasses migration history. For a migration-based project, use the migration workflow consistently.
  • Applying migrations during every production startup: Multiple API instances can make deployment behavior difficult to control. Prefer a reviewed SQL script, migration bundle, or dedicated migration job for production.

Practice Exercise

  1. Start the Compose stack containing SQL Server and its persistent volume.
  2. Verify the CatalogDbContext and Product entity.
  3. Create the InitialCreate migration locally or from an SDK container.
  4. Wait for the SQL Server health check to become healthy, then run dotnet ef database update.
  5. Verify the Products and __EFMigrationsHistory tables.
  6. Add the IsActive property, create AddProductStatus, and apply it.
  7. Restart the API container and send a request that reads or writes the new property.

Conclusion

EF Core migrations are not limited to commands executed on a developer workstation. They are an important part of a containerized development and deployment workflow. Migration files describe model changes as source code, while database update applies only the migrations that are missing from the target database.

It is also important to distinguish container startup from SQL Server readiness. A container may be running while the database engine is still initializing. Docker Compose health checks and depends_on.condition: service_healthy help reduce these startup races. In the next stage, migration execution can be integrated more deliberately into the application lifecycle and deployment process.

Sources