Course contentsShow
← C#
Lesson 1168 of 1,90810. Entity Framework Core ModelingFree lesson

Managing Database Migrations in Pipelines

Automate the database migration lifecycle within secure CI/CD environments.

In this lesson, you will learn how to transition from manual migration execution to an automated, secure CI/CD workflow for your EF Core database schema changes.

The Strategy: "Migrate-on-Deploy"

In a professional CI/CD environment, you should never manually run dotnet ef database update from a developer machine. Instead, you treat the migration as a first-class citizen of your deployment pipeline. The goal is to ensure the database schema is updated automatically whenever your application code is deployed, while maintaining strict security controls.

Implementation Patterns

There are two primary ways to handle this in a pipeline:

  1. The "Bundle" Approach (Recommended): Use dotnet ef migrations bundle. This command generates a self-contained, executable file that contains your migrations and the EF Core migration engine. In your pipeline, you simply copy this executable to the target environment and run it as a shell command.

    # Run this in your CI/CD build step
    dotnet ef migrations bundle --output ./migrate.exe
    

    During the deployment phase, the pipeline executes ./migrate.exe --connection "YourConnectionString". This is highly secure because it doesn’t require the full .NET SDK to be installed on your production servers.

  2. The "Startup Code" Approach: You can trigger migrations inside your application’s Program.cs on startup. While convenient, this is often discouraged for high-scale applications as multiple instances might race to update the schema. If you use this, always ensure you use a locking mechanism or a dedicated migration task to avoid conflicts.

Security and Reliability

When automating, your pipeline must use a service principal or managed identity to connect to the database, rather than a hardcoded connection string. Furthermore, always configure your pipeline to perform a schema-only migration test in a staging environment that mirrors production. This allows you to catch errors—such as data loss scenarios or incompatible schema changes—before they touch live customer data.

By bundling your migrations, you decouple the migration engine from the runtime environment, ensuring the database is always in sync with the deployed code version.

Key Takeaway: Automate your database schema updates by using migration bundles in your CI/CD pipeline, ensuring consistent, reproducible, and secure deployments without manual intervention.