This example demonstrates how to use DBMigrator with .NET Aspire for automated database migrations.
DBMigrator.Aspire.Example/
??? Program.cs # Aspire AppHost configuration
??? appsettings.json # Logging configuration
??? Migrations/ # Database migration scripts
??? 1.0/
??? UserManagement/
??? Migrations/
??? 1_CreateUsersTable.sql
??? 1_rollback_CreateUsersTable.sql
??? 2_AddEmailIndex.sql
-
Make sure you have .NET 9.0 SDK installed
-
Install .NET Aspire workload:
dotnet workload install aspire
-
Navigate to the example directory:
cd Examples/DBMigrator.Aspire.Example -
Run the application:
dotnet run
The Aspire dashboard will open in your browser, and you'll see:
- A SQL Server container being started
- DBMigrator running migrations before other resources start
- Migration logs in the dashboard
- SQL Server Container Starts: Aspire starts a SQL Server container
- Database Creation: The
exampledbdatabase is created - Migration Execution: DBMigrator lifecycle hook runs:
- Connects to the database
- Reads migration scripts from
./Migrations - Validates the database state
- Applies pending migrations (version 1.0)
- Creates the
Userstable - Adds an index on the
Emailcolumn
- Application Ready: Other resources can now start
- ? SQL Server integration with Aspire
- ? Automatic migration execution on startup
- ? Structured migration folder organization
- ? Version-based migrations (1.0)
- ? Feature-based organization (UserManagement)
- ? Rollback script support
- ? Comprehensive logging
To migrate to a different version, modify Program.cs:
var dbMigrator = builder.AddDBMigrator("dbmigrator", database, "./Migrations")
.WithTargetVersion("2.0"); // Change to your target versionFor development scenarios where you want to skip validation:
var dbMigrator = builder.AddDBMigrator("dbmigrator", database, "./Migrations")
.WithSkipValidation();Test migrations without committing:
var dbMigrator = builder.AddDBMigrator("dbmigrator", database, "./Migrations")
.WithDryRun();Integrate with your own API project:
var api = builder.AddProject<Projects.MyApi>("api")
.WithReference(database)
.WaitForDBMigrator(dbMigrator);This ensures your API only starts after migrations complete.
- Create a new version folder (e.g.,
2.0) - Create a feature folder inside it (e.g.,
ProductCatalog) - Create a
Migrationssubfolder - Add your SQL scripts following the naming convention:
- Upgrade:
<order>_<description>.sql - Rollback:
<order>_rollback_<description>.sql
- Upgrade:
Example:
Migrations/
??? 2.0/
??? ProductCatalog/
??? Migrations/
??? 1_CreateProductsTable.sql
??? 1_rollback_CreateProductsTable.sql
Check the Aspire dashboard logs for the DBMigrator resource to see any errors.
Ensure the SQL Server container is healthy before migrations run. The lifecycle hook waits for the container to be ready.
The migrations path is relative to the AppHost project directory. Make sure the path in AddDBMigrator correctly points to your migrations folder.