Aspire

Aspire database patterns

Most Aspire solutions include at least one database. During development you create that database, fill it with sample data, change its schema as your app evolves, and decide whether its data should survive a restart. When you deploy, you decide where the database runs and how schema changes reach it. This article describes the options Aspire gives you for each of these tasks, with examples you can adapt for your own solution.

The examples on this page use PostgreSQL but the same patterns apply to other database integrations such as SQL Server, MySQL, and MongoDB. Where an example needs an Object-Relational Mapper (ORM), it uses Entity Framework Core (EF Core) for .NET apps or Drizzle for JavaScript and TypeScript apps. Select your ORM to see only the examples that use it:

Select your ORM

Use this table to find the right approach for your requirements:

What do you want to do?Where do you want to do it?Options
Create a databaseIn the AppHostAdd a database resource
In an orchestrated appOn startup or with a custom command
In a dashboard REPL terminalRun commands or a script
Seed a databaseIn an orchestrated appOn startup or with a custom command
Use EF Core or Drizzle migrations
In a dashboard REPL terminalRun a script
Modify a database schemaIn an orchestrated appApply migrations on startup
Apply migrations with a custom command
In a dashboard REPL terminalRun a script
Persist a database across restartsIn the AppHostData volumes, bind mounts, and persistent lifetimes
Deploy a databaseIn the AppHostA container database or a managed database service

In this article, a script is any program that works with the database. It can be a SQL file, a shell script, or a program written in a language such as JavaScript or Python.

A database server, such as a PostgreSQL container, can host many databases. Your app needs a specific database on that server before it can create tables or store data. You can create that database from the AppHost, from your app’s code, or by hand in the dashboard.

The simplest way to create a database is to add a database resource to the server resource in your AppHost. The PostgreSQL resources in the examples on this page come from the 📦 Aspire.Hosting.PostgreSQL package. Call AddDatabaseaddDatabaseAddDatabase on the server resource, then reference the database from the app that uses it:

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');
const catalogdb = await postgres.addDatabase('catalogdb');
await builder.addNodeApp('api', './api', 'src/index.ts')
.withReference(catalogdb)
.waitFor(catalogdb);
await builder.build().run();

When the server resource is ready, Aspire creates the database if it doesn’t already exist. WithReferencewithReferenceWithReference passes the database’s connection information to the app, and WaitForwaitForWaitFor makes sure the app doesn’t start until the database is available.

To control how the database is created, for example to set a collation or an owner, replace the default creation script by using WithCreationScriptwithCreationScriptWithCreationScript. SQL Server and MySQL support the same method.

For more information, see Add PostgreSQL resource with database scripts. For details on how Aspire waits for the server to be ready, see AppHost eventing APIs.

Sometimes the app needs to create its own database. For example, the app might connect to an existing server that isn’t modeled in your AppHost, or it might create one database for each tenant. In this case, reference the server resource instead of a database resource, so the app receives a connection to the server.

EF Core can create the database for you. When an app applies migrations, EF Core creates the database first if it doesn’t exist. EnsureCreatedAsync also creates the database, but it bypasses migrations, so use it only for prototypes and tests.

When a .NET app references a PostgreSQL server resource named postgres, Aspire passes a connection string to the server, without a database name. Add the database name to the connection string when you register the DbContext, then apply migrations when the app starts. This example assumes a DbContext named CatalogContext:

Program.cs
using Microsoft.EntityFrameworkCore;
using Npgsql;
var builder = WebApplication.CreateBuilder(args);
builder.AddNpgsqlDbContext<CatalogContext>("postgres", configureSettings: settings =>
{
settings.ConnectionString = new NpgsqlConnectionStringBuilder(settings.ConnectionString)
{
Database = "catalogdb"
}.ConnectionString;
});
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
using var scope = app.Services.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<CatalogContext>();
// Creates catalogdb if it doesn't exist, then applies pending migrations.
await context.Database.MigrateAsync();
}
app.Run();

Drizzle doesn’t create databases. Instead, connect to the server and run a CREATE DATABASE statement before you run migrations. When a JavaScript app references a PostgreSQL server resource named postgres, Aspire passes the server’s connection URI in the POSTGRES_URI environment variable:

src/create-database.ts
import pg from 'pg';
const client = new pg.Client({ connectionString: process.env.POSTGRES_URI });
await client.connect();
const { rowCount } = await client.query(
'SELECT 1 FROM pg_database WHERE datname = $1', ['catalogdb']);
if (rowCount === 0) {
await client.query('CREATE DATABASE catalogdb');
}
await client.end();

You can run this code when the app starts, or from a custom command that you trigger from the dashboard. The Seed a database on startup or using a custom command section shows both approaches.

For the environment variables that Aspire passes to apps for each resource, see Connect to PostgreSQL.

Create a database in a dashboard REPL terminal

Section titled “Create a database in a dashboard REPL terminal”

To create a database by hand, open the database’s own command-line client in the dashboard. Call WithReplwithReplWithRepl on the server resource to add a REPL command. The command opens psql in the dashboard’s terminal dock, already signed in with the resource’s credentials:

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
await builder.addPostgres('postgres').withRepl();
await builder.build().run();

Run the app, then in the Aspire dashboard, select the REPL command on the postgres resource, and enter the statement:

psql
CREATE DATABASE catalogdb;

The SQL Server, MySQL, MongoDB, and Redis integrations also provide REPL commands. A database that you create by hand is lost when its container is removed, unless you persist the database.

For more information, see Open a database or cache REPL. For an overview of all terminal types, see Use interactive terminals in the dashboard.

Seeding fills a database with data before you use it, such as a product catalog or a set of test customers. Seed data lets you develop and test features against realistic content. Because database containers start empty by default, automate seeding so that every run starts from a known state.

When your app seeds the database, the seed logic lives in source control next to the model it depends on. You can run it every time the app starts, run it on demand, or include it in your migrations.

Seed a database on startup or using a custom command

Section titled “Seed a database on startup or using a custom command”

To seed on startup, run the seed code after the app connects to the database and before it handles requests. Make the code idempotent: check whether the data already exists before you insert it, so a restart doesn’t add duplicate rows.

Configure seeding with the UseSeeding and UseAsyncSeeding options when you register the DbContext. EF Core runs this code when the database is created or migrated. Implement both options with the same logic, because the EF Core tools call the synchronous UseSeeding option. The following example seeds a product only when it doesn’t exist, and registers the seed code only in development:

Program.cs
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.AddNpgsqlDbContext<CatalogContext>("catalogdb", configureDbContextOptions: options =>
{
if (!builder.Environment.IsDevelopment())
{
return;
}
options.UseSeeding((context, _) =>
{
var products = context.Set<Product>();
if (!products.Any(p => p.Name == "Sample product"))
{
products.Add(new Product { Name = "Sample product", Price = 9.99m });
context.SaveChanges();
}
});
options.UseAsyncSeeding(async (context, _, cancellationToken) =>
{
var products = context.Set<Product>();
if (!await products.AnyAsync(p => p.Name == "Sample product", cancellationToken))
{
products.Add(new Product { Name = "Sample product", Price = 9.99m });
await context.SaveChangesAsync(cancellationToken);
}
});
});
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
using var scope = app.Services.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<CatalogContext>();
// Applies pending migrations, then runs the UseAsyncSeeding code.
await context.Database.MigrateAsync();
}
app.Run();

To register the DbContext for SQL Server or MySQL instead, see Seed data using EF Core.

The drizzle-seed package generates realistic random data from your schema. The following example seeds the products table only when it’s empty:

src/seed.ts
import { drizzle } from 'drizzle-orm/node-postgres';
import { seed } from 'drizzle-seed';
import { products } from './schema.ts';
export async function seedDatabase() {
const db = drizzle(process.env.CATALOGDB_URI!);
const existing = await db.select().from(products).limit(1);
if (existing.length === 0) {
await seed(db, { products }, { count: 50 });
}
}

Call seedDatabase() when the app starts. Aspire passes the CATALOGDB_URI environment variable because the app references a database resource named catalogdb.

To seed only when you choose, expose the seed code as an endpoint in your app, then add a custom HTTP command to the app resource. The command appears in the dashboard, and selecting it sends a request to the endpoint.

The endpoint adds the rows through the database context. It checks for existing rows first, so you can run the command more than once:

Program.cs
using Microsoft.EntityFrameworkCore;
// After you build the app...
if (app.Environment.IsDevelopment())
{
app.MapPost("/admin/seed", async (CatalogContext context) =>
{
if (!await context.Products.AnyAsync())
{
context.Products.Add(new Product { Name = "Sample product", Price = 9.99m });
await context.SaveChangesAsync();
}
return Results.Ok(new { status = "Database seeded" });
});
}

Add the command to the app resource with WithHttpCommandwithHttpCommandWithHttpCommand:

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');
const catalogdb = await postgres.addDatabase('catalogdb');
await builder.addDotnetProject('api', '../Api/Api.csproj')
.withReference(catalogdb)
.waitFor(catalogdb)
.withHttpCommand('/admin/seed', 'Seed database', {
methodName: 'POST',
description: 'Adds sample data to the catalog database.',
confirmationMessage: 'Add sample data to the catalog database?',
});
await builder.build().run();

The endpoint calls the seedDatabase function from the previous example:

api/src/index.ts
import express from 'express';
import { seedDatabase } from './seed.ts';
const app = express();
if (process.env.NODE_ENV === 'development') {
app.post('/admin/seed', async (req, res) => {
await seedDatabase();
res.json({ status: 'Database seeded' });
});
}
// Add your other routes...
app.listen(process.env.PORT);

Add the command to the app resource with WithHttpCommandwithHttpCommandWithHttpCommand:

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');
const catalogdb = await postgres.addDatabase('catalogdb');
await builder.addNodeApp('api', './api', 'src/index.ts')
.withHttpEndpoint({ env: 'PORT' })
.withReference(catalogdb)
.waitFor(catalogdb)
.withHttpCommand('/admin/seed', 'Seed database', {
methodName: 'POST',
description: 'Adds sample data to the catalog database.',
confirmationMessage: 'Add sample data to the catalog database?',
});
await builder.build().run();

The HTTP endpoint passes its port to the app in the PORT environment variable. The app must listen on process.env.PORT, otherwise the command can’t reach it.

Protect seed endpoints so that only the AppHost can call them, and don’t expose them in production. The examples in Modify a schema with a custom command show how to send a shared secret with each request.

For more information, see Custom HTTP commands. To run logic in the AppHost itself instead of calling an endpoint, see Custom resource commands.

You can also include seed data in your migrations. The data is then applied in order with your schema changes, and it reaches every environment that runs the migrations. Use this approach for reference data that your app needs, such as a list of countries or order statuses, rather than for large sets of test data.

Call HasData in OnModelCreating to define seed rows as part of your model. Each row needs a primary key value:

CatalogContext.cs
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<OrderStatus>().HasData(
new OrderStatus { Id = 1, Name = "Pending" },
new OrderStatus { Id = 2, Name = "Shipped" },
new OrderStatus { Id = 3, Name = "Delivered" });
}

Then add a migration:

Terminal
dotnet ef migrations add SeedOrderStatuses

EF Core generates the insert, update, and delete statements needed to keep the rows in sync with the model. For more information, see Model managed data in the EF Core documentation.

Generate an empty custom migration:

Terminal
npx drizzle-kit generate --custom --name=seed-order-statuses

Drizzle Kit creates a SQL file in your migrations folder. Add your INSERT statements to that file:

api/drizzle/0001_seed-order-statuses.sql
INSERT INTO order_statuses (id, name) VALUES
(1, 'Pending'),
(2, 'Shipped'),
(3, 'Delivered');

Drizzle applies the file in order with your other migrations. Drizzle Kit sets the number prefix in the file name. For more information, see Custom migrations in the Drizzle documentation.

To learn how to apply migrations when your app runs, see Modify a database schema.

Seed a database in a dashboard REPL terminal

Section titled “Seed a database in a dashboard REPL terminal”

To add data by hand, open the database’s REPL from the dashboard as described in Create a database in a dashboard REPL terminal, then paste your INSERT statements. Use the REPL to try out data or to fix a single row. For seed data that you need every time, save it as a script so you can repeat the process.

To run a SQL script automatically when the database container initializes, mount a folder of scripts into the container with WithInitFileswithInitFilesWithInitFiles:

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');
await postgres.withInitFiles('./postgres-init');
await builder.build().run();

PostgreSQL runs the .sql and .sh files in the folder in alphabetical order, against the default postgres database. The scripts run before Aspire creates the databases in your AppHost, so a script that seeds catalogdb creates that database and connects to it first:

postgres-init/01-catalog.sql
CREATE DATABASE catalogdb;
\c catalogdb
CREATE TABLE IF NOT EXISTS products
(
id SERIAL PRIMARY KEY,
name TEXT UNIQUE NOT NULL,
price NUMERIC(10, 2) NOT NULL
);
INSERT INTO products (name, price)
VALUES
('Hiking boots', 89.99),
('Water bottle', 12.50),
('Trail map', 4.99)
ON CONFLICT DO NOTHING;

If your AppHost also adds catalogdb as a database resource, Aspire finds the existing database when it creates its databases and leaves it in place. An initialization script that creates tables can conflict with ORM migrations that create the same tables. Use initialization scripts for databases that your app doesn’t manage with migrations.

PostgreSQL runs these scripts only when it initializes an empty data directory. If you persist the database with a data volume, the scripts don’t run again until you remove the volume.

To run a separate seed program, add it to the AppHost as a resource that you start from the dashboard. Call WithExplicitStartwithExplicitStartWithExplicitStart so that the resource doesn’t run with the rest of the app. The resource receives the database’s connection information from its database reference, in the same way as the app.

This example adds a .NET console project that seeds the database. The project registers the DbContext in the same way as the app:

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');
const catalogdb = await postgres.addDatabase('catalogdb');
await builder.addDotnetProject('api-seed', '../SeedData/SeedData.csproj')
.withReference(catalogdb)
.waitFor(catalogdb)
.withExplicitStart();
await builder.build().run();

This example runs a db:seed script from the app’s package.json file:

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');
const catalogdb = await postgres.addDatabase('catalogdb');
await builder.addJavaScriptApp('api-seed', './api', { runScriptName: 'db:seed' })
.withReference(catalogdb)
.waitFor(catalogdb)
.withExplicitStart();
await builder.build().run();

To seed, select Start on the api-seed resource in the dashboard. The resource’s console logs show the script’s output. To run a tool that isn’t part of your app, such as a CLI installed on your machine, use a process-backed resource command instead. For more information, see Process-backed resource commands.

For initialization script examples for SQL Server and MySQL, see Seed data using SQL scripts.

As your app evolves, its tables and columns change. Most teams manage these changes with migrations: versioned files, kept in source control, that each describe one change to the schema. An ORM tracks which migrations a database has already applied, so it applies only the new ones. Your ORM generates migrations from changes to your model.

Run dotnet ef migrations add <name> to generate a C# migration from changes to your DbContext model. For more information, see Create migrations.

Run npx drizzle-kit generate to generate a SQL migration from changes to your schema file. For more information, see Migrations with Drizzle in the Drizzle documentation.

To keep the database schema in step with your code, apply pending migrations every time the app runs.

Add a migration resource to your AppHost with AddEFMigrationsaddEFMigrationsAddEFMigrations from the 📦 Aspire.Hosting.EntityFrameworkCore package. This package is in preview. Call RunDatabaseUpdateOnStartrunDatabaseUpdateOnStartRunDatabaseUpdateOnStart to apply migrations when the AppHost starts, and make the app wait for the migrations to finish with WaitForCompletionwaitForCompletionWaitForCompletion:

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');
const catalogdb = await postgres.addDatabase('catalogdb');
const api = await builder.addDotnetProject('api', '../Api/Api.csproj');
await api.withReference(catalogdb);
const migrations = await api.addEFMigrations('api-migrations');
await migrations.runDatabaseUpdateOnStart();
await api.waitForCompletion(migrations);
await builder.build().run();

If you prefer to apply EF Core migrations from your own code, create a worker service project that calls MigrateAsync and then exits. Register the DbContext and the worker in the project’s Program.cs file:

MigrationService/Program.cs
var builder = Host.CreateApplicationBuilder(args);
builder.AddServiceDefaults();
builder.AddNpgsqlDbContext<CatalogContext>("catalogdb");
builder.Services.AddHostedService<Worker>();
builder.Build().Run();

The worker applies the migrations inside an execution strategy, so EF Core retries them after a transient connection error. If the migrations fail, the worker sets a nonzero exit code. It then stops the app:

MigrationService/Worker.cs
using Microsoft.EntityFrameworkCore;
public class Worker(
IServiceProvider serviceProvider,
IHostApplicationLifetime lifetime) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
using var scope = serviceProvider.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<CatalogContext>();
var strategy = context.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(() => context.Database.MigrateAsync(stoppingToken));
}
catch
{
// The host exits with code 0 after a failed background service
// unless you set the exit code yourself.
Environment.ExitCode = 1;
throw;
}
finally
{
lifetime.StopApplication();
}
}
}

In the AppHost, add the worker project and make the app wait for it to finish:

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');
const catalogdb = await postgres.addDatabase('catalogdb');
const migrations = await builder.addDotnetProject('migrations', '../MigrationService/MigrationService.csproj')
.withReference(catalogdb)
.waitFor(catalogdb);
await builder.addDotnetProject('api', '../Api/Api.csproj')
.withReference(catalogdb)
.waitForCompletion(migrations);
await builder.build().run();

If the migrations fail, the worker exits with code 1, and the app doesn’t start because WaitForCompletion requires a successful exit. For a step-by-step tutorial that builds a migration service, see Apply EF Core migrations in Aspire.

Add a db:migrate script to the app’s package.json file that runs drizzle-kit migrate. Then add a second resource to your AppHost that runs this script, and make the app wait for it to finish. Add the resource with AddJavaScriptAppaddJavaScriptAppAddJavaScriptApp from the 📦 Aspire.Hosting.JavaScript package:

api/package.json
{
"scripts": {
"db:migrate": "drizzle-kit migrate"
}
}
apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');
const catalogdb = await postgres.addDatabase('catalogdb');
const migrate = await builder.addJavaScriptApp('api-migrate', './api', { runScriptName: 'db:migrate' })
.withReference(catalogdb)
.waitFor(catalogdb);
await builder.addNodeApp('api', './api', 'src/index.ts')
.withReference(catalogdb)
.waitForCompletion(migrate);
await builder.build().run();

App paths are relative to the AppHost. The TypeScript example assumes that apphost.mts is in the same folder as the api folder. The C# example assumes that the AppHost is in its own project folder, next to the api folder. Adjust the paths to match your solution layout.

Point the Drizzle Kit configuration at the connection URI that Aspire passes to the resource:

api/drizzle.config.ts
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
dialect: 'postgresql',
schema: './src/schema.ts',
out: './drizzle',
dbCredentials: {
url: process.env.CATALOGDB_URI!,
},
});

To apply Drizzle migrations from the app process instead, call the migrate function from drizzle-orm/node-postgres/migrator before the app starts handling requests. You don’t need the api-migrate resource with this approach:

api/src/index.ts
import express from 'express';
import { drizzle } from 'drizzle-orm/node-postgres';
import { migrate } from 'drizzle-orm/node-postgres/migrator';
const db = drizzle(process.env.CATALOGDB_URI!);
// Apply pending migrations before the app accepts requests.
await migrate(db, { migrationsFolder: './drizzle' });
const app = express();
// Add your routes...
app.listen(process.env.PORT);

If you run more than one replica of the app, each replica applies the migrations when it starts. Use a separate migration resource when only one process should change the schema.

For more information about the JavaScript hosting APIs, see Customize scripts.

For more information about waiting for resources, see Health checks.

Applying migrations on every run isn’t always what you want. For example, you might want to review a migration before you apply it, or apply it to a database that already holds data you care about. In these cases, apply the migrations on demand from a command in the dashboard.

When you add an EF Core migration resource without calling RunDatabaseUpdateOnStart, the resource doesn’t apply migrations on its own. It still appears in the dashboard, with commands that run the EF Core tools for that project. If your migrations are in a different project from the app, such as a data project, point the resource at that project with WithMigrationsProjectwithMigrationsProjectWithMigrationsProject:

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');
const catalogdb = await postgres.addDatabase('catalogdb');
const api = await builder.addDotnetProject('api', '../Api/Api.csproj');
await api.withReference(catalogdb);
// No RunDatabaseUpdateOnStart call, so migrations run only from the dashboard.
const migrations = await api.addEFMigrations('api-migrations');
await migrations.withMigrationsProject({ migrationsProject: '../Data/Data.csproj' });
await builder.build().run();

Pass the path to the migrations project, relative to the AppHost. If your migrations are in the app project, omit the call. For more information, see Automated EF migrations with AddEFMigrations.

You can also expose migrations as an endpoint in your app and call it with a custom HTTP command. Anyone who can reach the endpoint can change your schema, so the dashboard’s confirmation prompt isn’t enough protection on its own. Register the endpoint only in development, and require a shared secret that only the AppHost knows. The AppHost passes the secret to the app as an environment variable and sends it in a header when you run the command. For more information, see Considerations when registering HTTP commands.

The endpoint calls MigrateAsync on the database context. This example assumes that the app registers a DbContext named CatalogContext. For more information, see Use Aspire to create an EF Core context.

Program.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
// After you build the app...
if (app.Environment.IsDevelopment())
{
app.MapPost("/admin/migrate", async (
[FromHeader(Name = "X-Migration-Key")] string? key,
IConfiguration config,
CatalogContext context) =>
{
if (config["MIGRATION_KEY"] is not { Length: > 0 } expected || key != expected)
{
return Results.Unauthorized();
}
await context.Database.MigrateAsync();
return Results.Ok(new { status = "Migrations applied" });
});
}

Then add the command to the app resource in your AppHost. The AppHost generates a random key each time it starts, passes it to the app in the MIGRATION_KEY environment variable, and adds it to the command’s request in the X-Migration-Key header:

apphost.mts
import { randomBytes } from 'node:crypto';
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const migrationKey = randomBytes(32).toString('hex');
const postgres = await builder.addPostgres('postgres');
const catalogdb = await postgres.addDatabase('catalogdb');
await builder.addDotnetProject('api', '../Api/Api.csproj')
.withReference(catalogdb)
.waitFor(catalogdb)
.withEnvironment('MIGRATION_KEY', migrationKey)
.withHttpCommand('/admin/migrate', 'Apply migrations', {
methodName: 'POST',
confirmationMessage: 'Apply pending migrations to the catalog database?',
prepareRequest: async () => ({
headers: { 'X-Migration-Key': migrationKey },
}),
});
await builder.build().run();

To apply migrations on demand, expose them as an endpoint in your app and call it with a custom HTTP command. Anyone who can reach the endpoint can change your schema, so the dashboard’s confirmation prompt isn’t enough protection on its own. Register the endpoint only in development, and require a shared secret that only the AppHost knows. The AppHost passes the secret to the app as an environment variable and sends it in a header when you run the command. For more information, see Considerations when registering HTTP commands.

The endpoint calls the migrate function:

api/src/index.ts
import express from 'express';
import { drizzle } from 'drizzle-orm/node-postgres';
import { migrate } from 'drizzle-orm/node-postgres/migrator';
const app = express();
const db = drizzle(process.env.CATALOGDB_URI!);
const migrationKey = process.env.MIGRATION_KEY;
if (process.env.NODE_ENV === 'development' && migrationKey) {
app.post('/admin/migrate', async (req, res) => {
if (req.get('X-Migration-Key') !== migrationKey) {
res.sendStatus(401);
return;
}
await migrate(db, { migrationsFolder: './drizzle' });
res.json({ status: 'Migrations applied' });
});
}
// Add your other routes...
app.listen(process.env.PORT);

Then add the command to the app resource in your AppHost. The AppHost generates a random key each time it starts, passes it to the app in the MIGRATION_KEY environment variable, and adds it to the command’s request in the X-Migration-Key header:

apphost.mts
import { randomBytes } from 'node:crypto';
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const migrationKey = randomBytes(32).toString('hex');
const postgres = await builder.addPostgres('postgres');
const catalogdb = await postgres.addDatabase('catalogdb');
await builder.addNodeApp('api', './api', 'src/index.ts')
.withHttpEndpoint({ env: 'PORT' })
.withReference(catalogdb)
.waitFor(catalogdb)
.withEnvironment('MIGRATION_KEY', migrationKey)
.withHttpCommand('/admin/migrate', 'Apply migrations', {
methodName: 'POST',
confirmationMessage: 'Apply pending migrations to the catalog database?',
prepareRequest: async () => ({
headers: { 'X-Migration-Key': migrationKey },
}),
});
await builder.build().run();

The HTTP endpoint passes its port to the app in the PORT environment variable. The app must listen on process.env.PORT, otherwise the command can’t reach it.

Dashboard commands are available only when you run the dashboard locally. Don’t rely on them to migrate a deployed database. For deployment options, see Deploy a database with an Aspire solution.

For more information, see Custom HTTP commands and Custom resource commands.

Modify a schema in a dashboard REPL terminal

Section titled “Modify a schema in a dashboard REPL terminal”

You can also change a schema by hand. Open the database’s REPL from the dashboard, as described in Create a database in a dashboard REPL terminal, and run statements such as ALTER TABLE. This approach is useful when you experiment with a schema change before you write a migration for it.

By default, Aspire removes a database container when the AppHost stops, so the database and its data are lost. To keep the data between runs, store it outside the container:

To also keep the container itself running between runs, call WithPersistentLifetimewithPersistentLifetimeWithPersistentLifetime. A persistent container makes the AppHost start faster, but it doesn’t protect your data on its own. If the container is recreated, for example after a configuration change, its data is lost unless it’s stored in a volume. For databases, use a data volume and a persistent lifetime together:

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');
await postgres.withDataVolume();
await postgres.withPersistentLifetime();
const catalogdb = await postgres.addDatabase('catalogdb');
await builder.build().run();

In a C# AppHost, the persistent lifetime API is experimental and requires suppressing the ASPIREPERSISTENCE001 diagnostic.

When the data persists, plan how seed logic and initialization scripts behave on later runs. Initialization scripts run only against an empty data directory, and seed code should check for existing rows. Aspire generates the password on first run and stores it in the AppHost’s user secrets. Set it yourself if you want to control or share it.

When you deploy, the database resources in your AppHost become part of the deployment. You choose between two models:

  • Deploy the database as a container next to your app. The deployment target, such as Docker Compose, Kubernetes, or Azure Container Apps, runs the same database image that you use in development. Without a volume, the container starts with a new, empty database each time it’s replaced, so attach a volume to keep the data between deployments.
  • Use a managed database service, such as Azure Database for PostgreSQL or Azure SQL Database. The cloud provider stores the data, so it stays in place across deployments. Aspire creates the databases in your AppHost during the first deployment and doesn’t recreate or delete them later.

To use a managed service when you deploy and a local container during development, call RunAsContainer on the Azure resource. This example uses the 📦 Aspire.Hosting.Azure.PostgreSQL package:

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addAzurePostgresFlexibleServer('postgres');
await postgres.runAsContainer();
const catalogdb = await postgres.addDatabase('catalogdb');
await builder.addDotnetProject('api', '../Api/Api.csproj')
.withReference(catalogdb)
.waitFor(catalogdb);
await builder.build().run();
apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addAzurePostgresFlexibleServer('postgres');
await postgres.runAsContainer();
const catalogdb = await postgres.addDatabase('catalogdb');
await builder.addNodeApp('api', './api', 'src/index.ts')
.withReference(catalogdb)
.waitFor(catalogdb);
await builder.build().run();

When you run the app locally, Aspire starts a PostgreSQL container. When you deploy, it provisions Azure Database for PostgreSQL.

Your schema must also reach the deployed database, so plan how your migrations run when you deploy.

RunDatabaseUpdateOnStart affects only local runs. To apply migrations in a deployed environment, publish them as a container image with PublishAsMigrationBundlepublishAsMigrationBundlePublishAsMigrationBundle. The bundle is deployed with your app and applies pending migrations when it runs. If you want to review the SQL before it runs, call PublishAsMigrationScriptpublishAsMigrationScriptPublishAsMigrationScript instead. It generates an idempotent SQL script during aspire publish, which you then run against the database yourself.

A migration bundle container exits after it applies the migrations. Configure each deployment target so that it doesn’t restart the container:

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
await builder.addDockerComposeEnvironment('compose');
const postgres = await builder.addPostgres('postgres');
const catalogdb = await postgres.addDatabase('catalogdb');
const api = await builder.addDotnetProject('api', '../Api/Api.csproj');
await api.withReference(catalogdb);
const migrations = await api.addEFMigrations('api-migrations');
await migrations.withReference(catalogdb);
await migrations.waitFor(catalogdb);
await migrations.publishAsMigrationBundle({ publishContainer: true });
await migrations.publishAsDockerComposeService(async (resource, service) => {
await service.restart.set('no');
});
await builder.build().run();

The Docker Compose methods come from the 📦 Aspire.Hosting.Docker package. Call WithReference on the migration resource so that the bundle container receives the database connection string, and WaitFor so that Docker Compose starts it after the database container. Docker Compose waits for the container to start, not for the database to accept connections.

Run drizzle-kit migrate as a step in your CI/CD pipeline, or call the migrate function when the deployed app starts, as shown in Apply schema migrations on startup. To deploy the api-migrate resource from that section instead, call PublishAsPackageScriptpublishAsPackageScriptPublishAsPackageScript. The deployment then builds a container image that runs the db:migrate script. For other publishing options, see Deploy JavaScript apps.

The generated Dockerfile installs packages with npm ci and then runs npm run build, so the app needs a package-lock.json file and a build script. The app in these examples runs its TypeScript source directly with Node.js, so its build script only needs to succeed:

api/package.json
{
"scripts": {
"build": "echo \"No build step\"",
"db:migrate": "drizzle-kit migrate"
}
}

If your app’s build step uses another script name, select that script when you add the resource. For more information, see Customize scripts.

The api-migrate container exits after it applies the migrations. Configure each deployment target so that it doesn’t restart the container:

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
await builder.addDockerComposeEnvironment('compose');
const postgres = await builder.addPostgres('postgres');
const catalogdb = await postgres.addDatabase('catalogdb');
const migrate = await builder.addJavaScriptApp('api-migrate', './api', { runScriptName: 'db:migrate' })
.withReference(catalogdb)
.waitFor(catalogdb)
.publishAsPackageScript({ scriptName: 'db:migrate' });
await migrate.publishAsDockerComposeService(async (resource, service) => {
await service.restart.set('no');
});
await builder.addNodeApp('api', './api', 'src/index.ts')
.withReference(catalogdb)
.waitForCompletion(migrate);
await builder.build().run();

The Docker Compose methods come from the 📦 Aspire.Hosting.Docker package. The db:migrate script runs drizzle-kit in the container, so list drizzle-kit under dependencies in package.json, not devDependencies. A production image doesn’t have to include development dependencies.

Don’t deploy development seed data or seed endpoints. Seed data that’s part of your migrations, such as reference data, is deployed with the migrations.

When you deploy a new version of your app, the new code often expects the new schema. If the app starts before the migrations finish, or if the migrations fail, the app can fail at runtime. To prevent this, make the deployment apply migrations first, and stop it when they fail. Choose one of these approaches:

Either way, the app version that’s still running keeps serving requests while the migrations run. Write migrations that the old version of the app can tolerate. For example, add a column in one release and remove the old column in a later release.

The aspire deploy command runs a pipeline of named steps, such as provision-api-containerapp and deploy-api. You can add your own steps to this pipeline and declare which steps must run before and after them. To make the app deployment wait for the migrations, deploy the migrations as a job and add a step that:

  1. Runs after the step that creates or updates the migration job.
  2. Starts the job and waits for it to finish. If the job fails, the step throws an error, and the pipeline stops.
  3. Runs before the step that updates the app, so that the app is updated only after the migrations succeed.

The following examples deploy to Azure Container Apps, so they need the 📦 Aspire.Hosting.Azure.AppContainers package. Aspire creates or updates each container app or job in a step named provision-<resource-name>-containerapp. A manually triggered job doesn’t run when it’s deployed, so the custom step starts it with the az containerapp job start command and polls its status. To find the step names for your deployment target, run aspire do diagnostics, which prints the dependency graph of the pipeline.

Aspire creates the Azure deployment steps while it resolves the pipeline, after your AppHost code adds its own steps. To depend on an Azure step reliably, add your step without dependencies, then add the dependencies in a pipeline configuration callback. Aspire runs this callback after all the steps exist. The callback also runs during pipeline passes that don’t create the Azure steps, so it adds the dependencies only when it finds them.

Publish the migration bundle as a container image and deploy it as a manually triggered job with PublishAsAzureContainerAppJobpublishAsAzureContainerAppJobPublishAsAzureContainerAppJob. Then add the custom step and the configuration callback. In C#, use builder.Pipeline.AddStep and builder.Pipeline.AddPipelineConfiguration. In TypeScript, use pipeline.addStep and pipeline.configure:

apphost.mts
import { execFile } from 'node:child_process';
import { setTimeout as delay } from 'node:timers/promises';
import { promisify } from 'node:util';
import { createBuilder } from './.aspire/modules/aspire.mjs';
const run = promisify(execFile);
const builder = await createBuilder();
await builder.addAzureContainerAppEnvironment('env');
const postgres = await builder.addPostgres('postgres');
const catalogdb = await postgres.addDatabase('catalogdb');
const api = await builder.addDotnetProject('api', '../Api/Api.csproj');
await api.withReference(catalogdb);
// Deploy the migration bundle as a manually triggered job.
const migrations = await api.addEFMigrations('api-migrations');
await migrations.withReference(catalogdb);
await migrations.waitFor(catalogdb);
await migrations.publishAsMigrationBundle({ publishContainer: true });
await migrations.publishAsAzureContainerAppJob();
if (await builder.executionContext().isPublishMode()) {
const pipeline = await builder.pipeline();
await pipeline.addStep('run-api-migrations', async (context) => {
const logger = await context.logger();
const resourceGroup = process.env.Azure__ResourceGroup!;
const job = ['--name', 'api-migrations', '--resource-group', resourceGroup];
const { stdout } = await run('az', [
'containerapp', 'job', 'start', ...job,
'--query', 'name', '--output', 'tsv',
]);
const execution = stdout.trim();
await logger.logInformation(`Started migration job execution ${execution}.`);
while (true) {
await delay(10_000);
const { stdout: output } = await run('az', [
'containerapp', 'job', 'execution', 'show', ...job,
'--job-execution-name', execution,
'--query', 'properties.status', '--output', 'tsv',
]);
const status = output.trim();
if (status === 'Succeeded') {
await logger.logInformation('Migrations applied.');
return;
}
if (['Failed', 'Stopped', 'Degraded'].includes(status)) {
throw new Error(`Migration job execution ${execution} ended with status ${status}.`);
}
}
});
// Azure creates its deployment steps while the pipeline resolves,
// so add the dependencies in a configuration callback.
await pipeline.configure(async (context) => {
const steps = new Map();
for (const step of await (await context.pipeline()).steps()) {
steps.set(await step.name(), step);
}
const deployApp = steps.get('provision-api-containerapp');
if (steps.has('provision-api-migrations-containerapp') && deployApp) {
// Run after the migration job is created or updated,
await steps.get('run-api-migrations').dependsOn('provision-api-migrations-containerapp');
// and before the app is updated.
await deployApp.dependsOn('run-api-migrations');
}
});
}
await builder.build().run();

Deploy the db:migrate script from Apply schema migrations on startup as a job. Call PublishAsPackageScript to build a container image that runs the script, and deploy the image as a manually triggered job. Then add the custom step and the configuration callback for the api-migrate job. In C#, use builder.Pipeline.AddStep and builder.Pipeline.AddPipelineConfiguration. In TypeScript, use pipeline.addStep and pipeline.configure:

apphost.mts
import { execFile } from 'node:child_process';
import { setTimeout as delay } from 'node:timers/promises';
import { promisify } from 'node:util';
import { createBuilder } from './.aspire/modules/aspire.mjs';
const run = promisify(execFile);
const builder = await createBuilder();
await builder.addAzureContainerAppEnvironment('env');
const postgres = await builder.addPostgres('postgres');
const catalogdb = await postgres.addDatabase('catalogdb');
// Deploy the db:migrate script as a manually triggered job.
const migrate = await builder.addJavaScriptApp('api-migrate', './api', { runScriptName: 'db:migrate' })
.withReference(catalogdb)
.waitFor(catalogdb)
.publishAsPackageScript({ scriptName: 'db:migrate' });
await migrate.publishAsAzureContainerAppJob();
await builder.addNodeApp('api', './api', 'src/index.ts')
.withReference(catalogdb)
.waitForCompletion(migrate);
if (await builder.executionContext().isPublishMode()) {
const pipeline = await builder.pipeline();
await pipeline.addStep('run-api-migrations', async (context) => {
const logger = await context.logger();
const resourceGroup = process.env.Azure__ResourceGroup!;
const job = ['--name', 'api-migrate', '--resource-group', resourceGroup];
const { stdout } = await run('az', [
'containerapp', 'job', 'start', ...job,
'--query', 'name', '--output', 'tsv',
]);
const execution = stdout.trim();
await logger.logInformation(`Started migration job execution ${execution}.`);
while (true) {
await delay(10_000);
const { stdout: output } = await run('az', [
'containerapp', 'job', 'execution', 'show', ...job,
'--job-execution-name', execution,
'--query', 'properties.status', '--output', 'tsv',
]);
const status = output.trim();
if (status === 'Succeeded') {
await logger.logInformation('Migrations applied.');
return;
}
if (['Failed', 'Stopped', 'Degraded'].includes(status)) {
throw new Error(`Migration job execution ${execution} ended with status ${status}.`);
}
}
});
// Azure creates its deployment steps while the pipeline resolves,
// so add the dependencies in a configuration callback.
await pipeline.configure(async (context) => {
const steps = new Map();
for (const step of await (await context.pipeline()).steps()) {
steps.set(await step.name(), step);
}
const deployApp = steps.get('provision-api-containerapp');
if (steps.has('provision-api-migrate-containerapp') && deployApp) {
// Run after the migration job is created or updated,
await steps.get('run-api-migrations').dependsOn('provision-api-migrate-containerapp');
// and before the app is updated.
await deployApp.dependsOn('run-api-migrations');
}
});
}
await builder.build().run();

The db:migrate script runs drizzle-kit in the container, so list drizzle-kit under dependencies in package.json, not devDependencies. A production image doesn’t have to include development dependencies.

The custom step reads the resource group from the Azure__ResourceGroup environment variable, so set it when you run aspire deploy. The Azure CLI must be installed and signed in to the same subscription. On Windows, run az.cmd instead of az.

You can use the same pattern with other deployment targets. Replace the az commands with the commands that run a one-off job on your target, such as docker compose run or kubectl wait --for=condition=complete. Then depend on the steps that your target adds to the pipeline.

For more information, see Pipelines and app topology, Azure Container Apps jobs, and Jobs in Azure Container Apps in the Azure documentation.

Run migrations as a CI/CD pre-deployment step

Section titled “Run migrations as a CI/CD pre-deployment step”

To apply migrations before the app is deployed, run them from your CI/CD pipeline before you call aspire deploy. If they fail, the pipeline stops before the deployment starts.

An EF Core migration bundle is a single executable that applies your migrations to a database. It doesn’t need the .NET SDK or your source code, so you can run it from a CI/CD pipeline before you deploy.

To generate the bundle, publish the migration resource as a migration bundle. Set the target runtime to match your CI/CD agent, and make the bundle self-contained so that the agent doesn’t need the .NET runtime:

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');
const catalogdb = await postgres.addDatabase('catalogdb');
const api = await builder.addDotnetProject('api', '../Api/Api.csproj');
await api.withReference(catalogdb);
await api.addEFMigrations('api-migrations')
.publishAsMigrationBundle({ targetRuntime: 'linux-x64', selfContained: true });
await builder.build().run();

A pipeline step named <resource-name>-generate-migration-bundle generates the bundle and writes it to the efmigrations folder in the publish output. In your CI/CD pipeline, run that step on its own, run the bundle against the production database, and then deploy:

Terminal
# Generate the bundle at ./artifacts/efmigrations/api-migrations.
aspire do api-migrations-generate-migration-bundle --output-path ./artifacts
# Apply pending migrations. The command fails if any migration fails.
./artifacts/efmigrations/api-migrations --connection "$CATALOGDB_CONNECTION_STRING"
# Deploy the app only after the migrations succeed.
aspire deploy

Store the connection string in your CI/CD system’s secret store, and make sure the agent can reach the database through its firewall. The step that generates the bundle doesn’t deploy anything. You can run it in a build stage and pass the bundle to a later deployment stage as an artifact.

For more information, see Migration bundles in the EF Core documentation and the aspire do command.

Drizzle has no equivalent of an EF Core migration bundle. Instead, run drizzle-kit migrate in your CI/CD pipeline with the production connection string. The drizzle.config.ts file from Apply schema migrations on startup reads the connection string from the CATALOGDB_URI environment variable:

Terminal
# Apply pending migrations from the app folder. The command fails if any migration fails.
(cd api && CATALOGDB_URI="$CATALOGDB_CONNECTION_STRING" npx drizzle-kit migrate)
# Deploy the app only after the migrations succeed.
aspire deploy

Store the connection string in your CI/CD system’s secret store, and make sure the agent can reach the database through its firewall.