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

Handling Migrations in CI/CD Pipelines

Automate schema deployment using CLI tools within professional build pipelines.

In this lesson, you’ll learn how to move beyond running migrations manually by automating your schema updates within a CI/CD pipeline using the Entity Framework Core CLI.

From Manual Updates to Automation

In a professional environment, you should never run dotnet ef database update from a developer's machine against a production database. Doing so creates inconsistency and risks human error. Instead, we treat the database schema as part of the build artifact.

When your code hits the build server, you want the pipeline to generate a SQL script that reflects the pending migrations. This script is then applied to the target environment as part of the deployment process.

The Pipeline Strategy

To automate this, use the dotnet ef migrations script command. This command generates an idempotent SQL script that compares your current database state to your latest migration snapshot, ensuring only the necessary changes are applied.

In your YAML-based pipeline (e.g., Azure DevOps or GitHub Actions), your build step would look something like this:

# Generate the migration script as a text file
dotnet ef migrations script --idempotent --output ./deploy/migration.sql --project ./MyProject.csproj

Why Idempotent?

The --idempotent flag is critical for pipelines. It generates SQL that checks for the existence of the __EFMigrationsHistory table and individual migrations. If a migration has already been applied, the script skips it instead of failing. This allows your pipeline to run the same script across multiple environments—Staging, QA, and Production—without fear of "migration already exists" errors.

Once the .sql file is generated, your deployment task (like an Azure SQL Task or a SQL Server script execution tool) can execute this file against your target database using a service principal or managed identity. This ensures your schema stays perfectly synchronized with your application code without ever requiring manual intervention.

Key Takeaway: Automate schema deployment by generating idempotent SQL scripts during your CI build, ensuring consistency across environments without manual database access.