From 3fb8ba418d01a2c77541fde6caa540a146d0c1f9 Mon Sep 17 00:00:00 2001 From: AJ Matthews Date: Wed, 14 Oct 2026 17:48:03 +0100 Subject: [PATCH 01/13] Added a new page for the database patterns. --- .../databases/database-patterns.mdx | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 src/frontend/src/content/docs/integrations/databases/database-patterns.mdx diff --git a/src/frontend/src/content/docs/integrations/databases/database-patterns.mdx b/src/frontend/src/content/docs/integrations/databases/database-patterns.mdx new file mode 100644 index 0000000000..fafe9399c3 --- /dev/null +++ b/src/frontend/src/content/docs/integrations/databases/database-patterns.mdx @@ -0,0 +1,64 @@ +--- +title: Aspire Database patterns +seoTitle: Learn strategies for using databases in Aspire solutions +description: Learn about common patterns you can use to work with databases as you develop Aspire solutions. +--- + +> TODO: Astro imports as you go along + +> TODO: Intro paragraph here when you know more about the content. + +Use this table as the starting point: + +| Where do you want to run database code? | What language you you want to use? | What do you wan to do? | +|-----------------------------------------|------------------------------------|--------------------------| +| In the Aspire AppHost | .NET C# | Create a database | +| In a different resource | JavaScript | Update a database schema | +| In scripts | | Deploy a database | +| As SQL code in dashboard repl terminals | +| | + + + +Common tasks: + +- Create a DB +- Populate DB + - EF Core +- Modify DB Schema + - Migrations + - EF Core, .NET + - Drizzle, JavaScript +- Persist a DB across restarts +- Deployment + +Where: + +- In AppHost +- In orchestrated app + - Triggered on startup? + - Triggered by a custom command on the resource +- In code that runs in dashboard repl terminals + +| What do you want to do? | Where do you want to do it? | Options | +|------------------------------------|------------------------------|-----------------------------------------| +| Create a database | In the AppHost | AddDatabase | +| | In an orchestrated app | On startup/On custom command | +| | In a dashboard REPL terminal | Manual commands or script | +| Seed a database | In an orchestrated app | On startup/On custom command | +| | | EF Core/Drizzle | +| | In a dashboard REPL terminal | Script | +| Modify a database schema | In an orchestrated app | On startup/On custom command | +| | | EF Core/Drizzle | +| | In a dashboard REPL terminal | Script | +| Persist a database across restarts | In the AppHost | WithDataVolume | +| | | WithBindVolume | +| | | WithLifetime | +| Deployment | In the AppHost | New database on each deployment | +| | | Old databsae remains on each deployment | + + +Questions: +- When material is already covered elsewhere, duplicate, link to other document or link other document to this one? + +> NOTE: Scripts are any kind of script - not just SQL From 6205d00dd9bc4929fca6aec5db8138de3cb2b76a Mon Sep 17 00:00:00 2001 From: AJ Matthews Date: Thu, 15 Oct 2026 14:14:15 +0100 Subject: [PATCH 02/13] Started on the structure of the new DB article. --- .../config/sidebar/integrations.topics.ts | 4 ++ .../databases/database-patterns.mdx | 63 +++++++++---------- 2 files changed, 33 insertions(+), 34 deletions(-) diff --git a/src/frontend/config/sidebar/integrations.topics.ts b/src/frontend/config/sidebar/integrations.topics.ts index 391630f18b..3dda5f516c 100644 --- a/src/frontend/config/sidebar/integrations.topics.ts +++ b/src/frontend/config/sidebar/integrations.topics.ts @@ -902,6 +902,10 @@ export const integrationTopics: StarlightSidebarTopicsUserConfig = { 'zh-CN': '数据库', }, items: [ + { + label: 'Database patterns', + slug: 'integrations/databases/database-patterns', + }, { label: 'ClickHouse', collapsed: true, diff --git a/src/frontend/src/content/docs/integrations/databases/database-patterns.mdx b/src/frontend/src/content/docs/integrations/databases/database-patterns.mdx index fafe9399c3..d1ff97506b 100644 --- a/src/frontend/src/content/docs/integrations/databases/database-patterns.mdx +++ b/src/frontend/src/content/docs/integrations/databases/database-patterns.mdx @@ -10,35 +10,6 @@ description: Learn about common patterns you can use to work with databases as y Use this table as the starting point: -| Where do you want to run database code? | What language you you want to use? | What do you wan to do? | -|-----------------------------------------|------------------------------------|--------------------------| -| In the Aspire AppHost | .NET C# | Create a database | -| In a different resource | JavaScript | Update a database schema | -| In scripts | | Deploy a database | -| As SQL code in dashboard repl terminals | -| | - - - -Common tasks: - -- Create a DB -- Populate DB - - EF Core -- Modify DB Schema - - Migrations - - EF Core, .NET - - Drizzle, JavaScript -- Persist a DB across restarts -- Deployment - -Where: - -- In AppHost -- In orchestrated app - - Triggered on startup? - - Triggered by a custom command on the resource -- In code that runs in dashboard repl terminals | What do you want to do? | Where do you want to do it? | Options | |------------------------------------|------------------------------|-----------------------------------------| @@ -46,19 +17,43 @@ Where: | | In an orchestrated app | On startup/On custom command | | | In a dashboard REPL terminal | Manual commands or script | | Seed a database | In an orchestrated app | On startup/On custom command | -| | | EF Core/Drizzle | +| | | Use EF Core/Drizzle migrations | | | In a dashboard REPL terminal | Script | | Modify a database schema | In an orchestrated app | On startup/On custom command | -| | | EF Core/Drizzle | +| | | Use EF Core/Drizzle migrations | | | In a dashboard REPL terminal | Script | | Persist a database across restarts | In the AppHost | WithDataVolume | | | | WithBindVolume | | | | WithLifetime | -| Deployment | In the AppHost | New database on each deployment | +| Deploy a database | In the AppHost | New database on each deployment | | | | Old databsae remains on each deployment | -Questions: -- When material is already covered elsewhere, duplicate, link to other document or link other document to this one? +> Questions: +> - When material is already covered elsewhere, duplicate, link to other document or link other document to this one? > NOTE: Scripts are any kind of script - not just SQL + +## Create a database + +### Create a database in the AppHost + +### Create a database in an orchestrated app + +### Create a database in a dashboard REPL terminal + +## Seed a database with sample data + +### Seed a database in an orchestrated app + +#### Seed a database on startup or using a customer command + +#### Seed a database using ORM migrations + +### Seed a database in a dashboard REPL terminal + +## Modify a database schema + +## Persist a database across restarts + +## Deploy a database with an Aspire solution From 5e28293a227b011230a7ecdc85988b8bcb07c1cf Mon Sep 17 00:00:00 2001 From: AJ Matthews Date: Tue, 20 Oct 2026 15:48:01 +0100 Subject: [PATCH 03/13] Moved database patterns outline doc to Foundations. --- src/frontend/config/sidebar/docs.topics.ts | 4 ++++ src/frontend/config/sidebar/integrations.topics.ts | 4 ---- .../databases => fundamentals}/database-patterns.mdx | 0 3 files changed, 4 insertions(+), 4 deletions(-) rename src/frontend/src/content/docs/{integrations/databases => fundamentals}/database-patterns.mdx (100%) diff --git a/src/frontend/config/sidebar/docs.topics.ts b/src/frontend/config/sidebar/docs.topics.ts index 5658de5f3f..76d5043e94 100644 --- a/src/frontend/config/sidebar/docs.topics.ts +++ b/src/frontend/config/sidebar/docs.topics.ts @@ -824,6 +824,10 @@ export const docsTopics: StarlightSidebarTopicsUserConfig = { 'zh-CN': '数据与存储', }, items: [ + { + label: 'Database patterns', + slug: 'fundamentals/database-patterns', + }, { label: 'Persist data with volumes', slug: 'fundamentals/persist-data-volumes', diff --git a/src/frontend/config/sidebar/integrations.topics.ts b/src/frontend/config/sidebar/integrations.topics.ts index 3dda5f516c..391630f18b 100644 --- a/src/frontend/config/sidebar/integrations.topics.ts +++ b/src/frontend/config/sidebar/integrations.topics.ts @@ -902,10 +902,6 @@ export const integrationTopics: StarlightSidebarTopicsUserConfig = { 'zh-CN': '数据库', }, items: [ - { - label: 'Database patterns', - slug: 'integrations/databases/database-patterns', - }, { label: 'ClickHouse', collapsed: true, diff --git a/src/frontend/src/content/docs/integrations/databases/database-patterns.mdx b/src/frontend/src/content/docs/fundamentals/database-patterns.mdx similarity index 100% rename from src/frontend/src/content/docs/integrations/databases/database-patterns.mdx rename to src/frontend/src/content/docs/fundamentals/database-patterns.mdx From 47552961c241f8bb6657b211e409927f573938d6 Mon Sep 17 00:00:00 2001 From: AJ Matthews Date: Tue, 20 Oct 2026 17:30:06 +0100 Subject: [PATCH 04/13] First draft of DB patterns doc. --- .../docs/fundamentals/database-patterns.mdx | 624 +++++++++++++++++- 1 file changed, 598 insertions(+), 26 deletions(-) diff --git a/src/frontend/src/content/docs/fundamentals/database-patterns.mdx b/src/frontend/src/content/docs/fundamentals/database-patterns.mdx index d1ff97506b..105ad3326f 100644 --- a/src/frontend/src/content/docs/fundamentals/database-patterns.mdx +++ b/src/frontend/src/content/docs/fundamentals/database-patterns.mdx @@ -4,56 +4,628 @@ seoTitle: Learn strategies for using databases in Aspire solutions description: Learn about common patterns you can use to work with databases as you develop Aspire solutions. --- -> TODO: Astro imports as you go along +import { Tabs, TabItem } from '@astrojs/starlight/components'; +import LearnMore from '@components/LearnMore.astro'; +import ApiReference from '@components/ApiReference.astro'; -> TODO: Intro paragraph here when you know more about the content. +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 and links to the articles that cover each option in detail. -Use this table as the starting point: +The examples 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 shows both Entity Framework Core (EF Core) for .NET apps and Drizzle for JavaScript and TypeScript apps. +Use this table to find the right approach: -| What do you want to do? | Where do you want to do it? | Options | -|------------------------------------|------------------------------|-----------------------------------------| -| Create a database | In the AppHost | AddDatabase | -| | In an orchestrated app | On startup/On custom command | -| | In a dashboard REPL terminal | Manual commands or script | -| Seed a database | In an orchestrated app | On startup/On custom command | -| | | Use EF Core/Drizzle migrations | -| | In a dashboard REPL terminal | Script | -| Modify a database schema | In an orchestrated app | On startup/On custom command | -| | | Use EF Core/Drizzle migrations | -| | In a dashboard REPL terminal | Script | -| Persist a database across restarts | In the AppHost | WithDataVolume | -| | | WithBindVolume | -| | | WithLifetime | -| Deploy a database | In the AppHost | New database on each deployment | -| | | Old databsae remains on each deployment | +| What do you want to do? | Where do you want to do it? | Options | +| ----------------------- | --------------------------- | ------- | +| Create a database | In the AppHost | [Add a database resource](#create-a-database-in-the-apphost) | +| | In an orchestrated app | [On startup or with a custom command](#create-a-database-in-an-orchestrated-app) | +| | In a dashboard REPL terminal | [Run commands or a script](#create-a-database-in-a-dashboard-repl-terminal) | +| Seed a database | In an orchestrated app | [On startup or with a custom command](#seed-a-database-on-startup-or-using-a-custom-command) | +| | | [Use EF Core or Drizzle migrations](#seed-a-database-using-orm-migrations) | +| | In a dashboard REPL terminal | [Run a script](#seed-a-database-in-a-dashboard-repl-terminal) | +| Modify a database schema | In an orchestrated app | [Apply migrations on startup](#apply-schema-migrations-on-startup) | +| | | [Apply migrations with a custom command](#modify-a-schema-with-a-custom-command) | +| | In a dashboard REPL terminal | [Run a script](#modify-a-schema-in-a-dashboard-repl-terminal) | +| Persist a database across restarts | In the AppHost | [Data volumes, bind mounts, and persistent lifetimes](#persist-a-database-across-restarts) | +| Deploy a database | In the AppHost | [A container database or a managed database service](#deploy-a-database-with-an-aspire-solution) | - -> Questions: -> - When material is already covered elsewhere, duplicate, link to other document or link other document to this one? - -> NOTE: Scripts are any kind of script - not just SQL +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, Python, or C#. ## Create a database +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. + ### Create a database in the AppHost +The simplest way to create a database is to add a database resource to the server resource in your AppHost. Call on the server resource, then reference the database from the app that uses it: + + + + +```typescript title="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(); +``` + + + + +```csharp title="AppHost.cs" +var builder = DistributedApplication.CreateBuilder(args); + +var postgres = builder.AddPostgres("postgres"); +var catalogdb = postgres.AddDatabase("catalogdb"); + +builder.AddProject("api") + .WithReference(catalogdb) + .WaitFor(catalogdb); + +builder.Build().Run(); +``` + + + + +When the server resource is ready, Aspire creates the database if it doesn't already exist. The reference passes the database's connection information to the app, and the wait 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 with . SQL Server and MySQL support the same method. + + + For more information, see [Add PostgreSQL resource with database scripts](/integrations/databases/postgres/postgres-host/#add-postgresql-resource-with-database-scripts). For details on how Aspire waits for the server to be ready, see [AppHost eventing APIs](/app-host/eventing/). + + ### Create a database in an orchestrated app +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. For an example that runs this code on startup, see [Seed data manually](/integrations/databases/efcore/seed-database/#seed-data-manually). + +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: + +```typescript title="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](#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](/integrations/databases/postgres/postgres-connect/). + + ### 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 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: + + + + +```typescript title="apphost.mts" +import { createBuilder } from './.aspire/modules/aspire.mjs'; + +const builder = await createBuilder(); + +await builder.addPostgres('postgres').withRepl(); + +await builder.build().run(); +``` + + + + +```csharp title="AppHost.cs" +var builder = DistributedApplication.CreateBuilder(args); + +builder.AddPostgres("postgres").WithRepl(); + +builder.Build().Run(); +``` + + + + +Run the app, select the **REPL** command on the `postgres` resource, and enter the statement: + +```sql title="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](#persist-a-database-across-restarts). + +:::caution +The REPL uses the resource's credentials and can modify or delete any data. Enable it only for trusted dashboard users. +::: + + + For more information, see [Open a database or cache REPL](/dashboard/ephemeral-terminals/#open-a-database-or-cache-repl). For an overview of all terminal types, see [Use interactive terminals in the dashboard](/dashboard/terminals/). + + ## Seed a database with sample data +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. + ### Seed a database in an orchestrated app -#### Seed a database on startup or using a customer command +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 + +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. + +With EF Core, 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. For complete examples for SQL Server, PostgreSQL, and MySQL, see [Seed data using EF Core](/integrations/databases/efcore/seed-database/#seed-data-using-ef-core). + +With Drizzle, the `drizzle-seed` package generates realistic random data from your schema. The following example seeds the `products` table only when it's empty: + +```typescript title="src/seed.ts" +import { drizzle } from 'drizzle-orm/node-postgres'; +import { seed } from 'drizzle-seed'; +import { products } from './schema'; + +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. Add the command with : + + + + +```typescript title="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() + .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(); +``` + + + + +```csharp title="AppHost.cs" +var builder = DistributedApplication.CreateBuilder(args); + +var postgres = builder.AddPostgres("postgres"); +var catalogdb = postgres.AddDatabase("catalogdb"); + +builder.AddProject("api") + .WithReference(catalogdb) + .WaitFor(catalogdb) + .WithHttpCommand( + path: "/admin/seed", + displayName: "Seed database", + commandOptions: new HttpCommandOptions + { + Method = HttpMethod.Post, + Description = "Adds sample data to the catalog database.", + ConfirmationMessage = "Add sample data to the catalog database?" + }); + +builder.Build().Run(); +``` + + + + +Protect seed endpoints so that only the AppHost can call them, and don't expose them in production. For a way to send a shared secret with each request, see [Considerations when registering HTTP commands](/fundamentals/http-commands/#considerations-when-registering-http-commands). + + + For more information, see [Custom HTTP commands](/fundamentals/http-commands/). To run logic in the AppHost itself instead of calling an endpoint, see [Custom resource commands](/fundamentals/custom-resource-commands/). + #### Seed a database using ORM migrations -### Seed a database in a dashboard REPL terminal +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. + +With EF Core, call `HasData` in `OnModelCreating` to define seed rows as part of your model. When you add a migration, 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](https://learn.microsoft.com/ef/core/modeling/data-seeding#model-managed-data) in the EF Core documentation. + +With Drizzle, generate an empty custom migration and add your own SQL to it: + +```bash title="Terminal" +npx drizzle-kit generate --custom --name=seed-order-statuses +``` + +Drizzle Kit creates a SQL file in your migrations folder. Add `INSERT` statements to that file, and Drizzle applies it in order with your other migrations. For more information, see [Custom migrations](https://orm.drizzle.team/docs/kit-custom-migrations) in the Drizzle documentation. + +To learn how to apply migrations when your app runs, see [Modify a database schema](#modify-a-database-schema). + +### 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](#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 : + + + + +```typescript title="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(); +``` + + + + +```csharp title="AppHost.cs" +var builder = DistributedApplication.CreateBuilder(args); + +builder.AddPostgres("postgres") + .WithInitFiles("./postgres-init"); + +builder.Build().Run(); +``` + + + + +PostgreSQL runs these scripts only when it initializes an empty data directory. If you [persist the database](#persist-a-database-across-restarts) with a data volume, the scripts don't run again until you remove the volume. + +To run a script written in another language, such as a Node.js or Python seed program, start it from a resource command. A process-backed command runs a local program on the AppHost machine and shows its output in the dashboard. For more information, see [Process-backed resource commands](/fundamentals/custom-resource-commands/#process-backed-resource-commands). + + + For complete SQL seeding examples for SQL Server, PostgreSQL, and MySQL, see [Seed data using SQL scripts](/integrations/databases/efcore/seed-database/#seed-data-using-sql-scripts). + ## Modify a database schema +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. Both EF Core and Drizzle generate migrations from changes to your model: + +- With EF Core, run `dotnet ef migrations add ` to generate a C# migration from changes to your `DbContext` model. For more information, see [Create migrations](/integrations/databases/efcore/migrations/#create-migrations). +- With Drizzle, run `npx drizzle-kit generate` to generate a SQL migration from changes to your schema file. For more information, see [Migrations with Drizzle](https://orm.drizzle.team/docs/migrations) in the Drizzle documentation. + +### Apply schema migrations on startup + +To keep the database schema in step with your code, apply pending migrations every time the app runs. + +For EF Core, add a migration resource to your AppHost with from the [📦 Aspire.Hosting.EntityFrameworkCore](https://www.nuget.org/packages/Aspire.Hosting.EntityFrameworkCore) package. This package is in preview. Call to apply migrations when the AppHost starts, and make the app wait for the migrations to finish with : + + + + +```typescript title="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.addProject('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(); +``` + + + + +```csharp title="AppHost.cs" +var builder = DistributedApplication.CreateBuilder(args); + +var postgres = builder.AddPostgres("postgres"); +var catalogdb = postgres.AddDatabase("catalogdb"); + +var api = builder.AddProject("api") + .WithReference(catalogdb); + +var migrations = api.AddEFMigrations("api-migrations") + .RunDatabaseUpdateOnStart(); + +api.WaitForCompletion(migrations); + +builder.Build().Run(); +``` + + + + +If you prefer to apply EF Core migrations from your own code, create a worker service that calls `MigrateAsync` and exits. For a step-by-step guide, see [Create the migration service](/integrations/databases/efcore/migrations/#create-the-migration-service). + +For Drizzle, 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 : + +```json title="api/package.json" +{ + "scripts": { + "db:migrate": "drizzle-kit migrate" + } +} +``` + + + + +```typescript title="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', 'db:migrate') + .withReference(catalogdb) + .waitFor(catalogdb); + +await builder.addNodeApp('api', './api', 'src/index.ts') + .withReference(catalogdb) + .waitForCompletion(migrate); + +await builder.build().run(); +``` + + + + +```csharp title="AppHost.cs" +var builder = DistributedApplication.CreateBuilder(args); + +var postgres = builder.AddPostgres("postgres"); +var catalogdb = postgres.AddDatabase("catalogdb"); + +var migrate = builder.AddJavaScriptApp("api-migrate", "../api", "db:migrate") + .WithReference(catalogdb) + .WaitFor(catalogdb); + +builder.AddNodeApp("api", "../api", "src/index.ts") + .WithReference(catalogdb) + .WaitForCompletion(migrate); + +builder.Build().Run(); +``` + + + + +Point the Drizzle Kit configuration at the connection URI that Aspire passes to the resource: + +```typescript title="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. + + + For more information about the JavaScript hosting APIs, see [Customize scripts](/integrations/frameworks/javascript/#customize-scripts). For more information about waiting for resources, see [Health checks](/fundamentals/health-checks/). + + +### Modify a schema with a custom command + +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. For more information, see [Automated EF migrations with `AddEFMigrations`](/integrations/databases/efcore/migrations/#automated-ef-migrations-with-addefmigrations). + +For any ORM, you can also expose migrations as an endpoint in your app and call it with a custom HTTP command. With Drizzle, the endpoint calls the `migrate` function: + +```typescript title="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!); + +app.post('/admin/migrate', async (_req, res) => { + await migrate(db, { migrationsFolder: './drizzle' }); + res.json({ status: 'Migrations applied' }); +}); + +// Add your other routes, then start the server... +``` + +With EF Core, the endpoint calls `MigrateAsync` on the database context: + +```csharp title="Program.cs" +app.MapPost("/admin/migrate", async (CatalogContext context) => +{ + await context.Database.MigrateAsync(); + return Results.Ok(new { status = "Migrations applied" }); +}); +``` + +Then add the command to the app resource in your AppHost: + + + + +```typescript title="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() + .withReference(catalogdb) + .waitFor(catalogdb) + .withHttpCommand('/admin/migrate', 'Apply migrations', { + methodName: 'POST', + confirmationMessage: 'Apply pending migrations to the catalog database?', + }); + +await builder.build().run(); +``` + + + + +```csharp title="AppHost.cs" +var builder = DistributedApplication.CreateBuilder(args); + +var postgres = builder.AddPostgres("postgres"); +var catalogdb = postgres.AddDatabase("catalogdb"); + +builder.AddProject("api") + .WithReference(catalogdb) + .WaitFor(catalogdb) + .WithHttpCommand( + path: "/admin/migrate", + displayName: "Apply migrations", + commandOptions: new HttpCommandOptions + { + Method = HttpMethod.Post, + ConfirmationMessage = "Apply pending migrations to the catalog database?" + }); + +builder.Build().Run(); +``` + + + + +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](#deploy-a-database-with-an-aspire-solution). + + + For more information, see [Custom HTTP commands](/fundamentals/http-commands/) and [Custom resource commands](/fundamentals/custom-resource-commands/). + + +### 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](#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. + +:::caution +An ORM doesn't know about changes that you make by hand. If you use migrations, a manual change can make the database differ from what the ORM expects, and later migrations can fail. Capture every change that you want to keep in a migration. +::: + ## Persist a database across restarts +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: + +- Call to store the data in a volume that the container runtime manages. Use a volume in most cases. +- Call to store the data in a folder on your machine. Use a bind mount when you need to open the data files directly. + +To also keep the container itself running between runs, call . 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: + + + + +```typescript title="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(); +``` + + + + +```csharp title="AppHost.cs" +#pragma warning disable ASPIREPERSISTENCE001 + +var builder = DistributedApplication.CreateBuilder(args); + +var postgres = builder.AddPostgres("postgres") + .WithDataVolume() + .WithPersistentLifetime(); + +var catalogdb = postgres.AddDatabase("catalogdb"); + +builder.Build().Run(); +``` + + + + +In a C# AppHost, the persistent lifetime API is experimental and requires suppressing the [`ASPIREPERSISTENCE001`](/diagnostics/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. By default, Aspire generates a new server password on every run. Set the password as a secret or a parameter, so that the server can still open its existing data on the next run. + + + For more information, see [Persist Aspire data with volumes and binds](/fundamentals/persist-data-volumes/), [Create persistent passwords](/fundamentals/persist-data-volumes/#create-persistent-passwords), and [Container lifetime vs. data durability](/app-host/resource-lifetimes/#container-lifetime-vs-data-durability). + + ## Deploy a database with an Aspire solution + +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 keep using a local container during development, call `RunAsContainer` on the Azure resource. + +Your schema must also reach the deployed database. `RunDatabaseUpdateOnStart` affects only local runs, so plan a separate step for deployment: + +- With EF Core, publish your migrations as a container image with `PublishAsMigrationBundle`. The bundle runs as part of the deployment and applies pending migrations. For more information, see [Publish the migration bundle as a container image](/integrations/databases/efcore/migrations/#publish-the-migration-bundle-as-a-container-image). +- With Drizzle, the migration resource from [Apply schema migrations on startup](#apply-schema-migrations-on-startup) is deployed like any other app resource. Make sure it runs once and then stops, or call the `migrate` function when the app starts. Alternatively, run `drizzle-kit migrate` as a step in your CI/CD pipeline. + +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. + + + For more information, see [Deploy with Aspire](/deployment/deploy-with-aspire/), [Persistent volumes on Kubernetes](/deployment/kubernetes/persistent-volumes/), [Run as a local container during development](/integrations/cloud/azure/azure-postgresql/azure-postgresql-host/#run-as-a-local-container-during-development), and [Database creation after initial deployment](/integrations/cloud/azure/azure-postgresql/azure-postgresql-host/#database-creation-after-initial-deployment). + + +## See also + +- [PostgreSQL integration](/integrations/databases/postgres/postgres-host/) +- [Entity Framework Core integrations overview](/integrations/databases/efcore/overview/) +- [Apply EF Core migrations in Aspire](/integrations/databases/efcore/migrations/) +- [Seed data in a database using Aspire](/integrations/databases/efcore/seed-database/) +- [JavaScript integration](/integrations/frameworks/javascript/) +- [Drizzle ORM documentation](https://orm.drizzle.team/docs/overview) +- [EF Core documentation](https://learn.microsoft.com/ef/core/) From 1ffe449111fcc32896d7fee495a148daac006b54 Mon Sep 17 00:00:00 2001 From: AJ Matthews Date: Wed, 21 Oct 2026 17:02:22 +0100 Subject: [PATCH 05/13] Small style adjustments. --- .../content/docs/fundamentals/database-patterns.mdx | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/frontend/src/content/docs/fundamentals/database-patterns.mdx b/src/frontend/src/content/docs/fundamentals/database-patterns.mdx index 105ad3326f..1fe75417a5 100644 --- a/src/frontend/src/content/docs/fundamentals/database-patterns.mdx +++ b/src/frontend/src/content/docs/fundamentals/database-patterns.mdx @@ -10,9 +10,9 @@ import ApiReference from '@components/ApiReference.astro'; 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 and links to the articles that cover each option in detail. -The examples 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 shows both Entity Framework Core (EF Core) for .NET apps and Drizzle for JavaScript and TypeScript apps. +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 shows both Entity Framework Core (EF Core) for .NET apps and Drizzle for JavaScript and TypeScript apps. -Use this table to find the right approach: +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 | | ----------------------- | --------------------------- | ------- | @@ -28,7 +28,7 @@ Use this table to find the right approach: | Persist a database across restarts | In the AppHost | [Data volumes, bind mounts, and persistent lifetimes](#persist-a-database-across-restarts) | | Deploy a database | In the AppHost | [A container database or a managed database service](#deploy-a-database-with-an-aspire-solution) | -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, Python, or C#. +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. ## Create a database @@ -75,9 +75,9 @@ builder.Build().Run(); -When the server resource is ready, Aspire creates the database if it doesn't already exist. The reference passes the database's connection information to the app, and the wait makes sure the app doesn't start until the database is available. +When the server resource is ready, Aspire creates the database if it doesn't already exist. passes the database's connection information to the app, and 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 with . SQL Server and MySQL support the same method. +To control how the database is created, for example to set a collation or an owner, replace the default creation script by using . SQL Server and MySQL support the same method. For more information, see [Add PostgreSQL resource with database scripts](/integrations/databases/postgres/postgres-host/#add-postgresql-resource-with-database-scripts). For details on how Aspire waits for the server to be ready, see [AppHost eventing APIs](/app-host/eventing/). @@ -144,7 +144,7 @@ builder.Build().Run(); -Run the app, select the **REPL** command on the `postgres` resource, and enter the statement: +Run the app, then in the Aspire dashboard, select the **REPL** command on the `postgres` resource, and enter the statement: ```sql title="psql" CREATE DATABASE catalogdb; From 9c3f20cf382ed27128ab34aa78c505454564fd12 Mon Sep 17 00:00:00 2001 From: AJ Matthews Date: Wed, 21 Oct 2026 17:38:27 +0100 Subject: [PATCH 06/13] Fixes after running the doc-tester skill. --- .../docs/fundamentals/database-patterns.mdx | 26 +++++++++++++------ 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/src/frontend/src/content/docs/fundamentals/database-patterns.mdx b/src/frontend/src/content/docs/fundamentals/database-patterns.mdx index 1fe75417a5..432cbd435c 100644 --- a/src/frontend/src/content/docs/fundamentals/database-patterns.mdx +++ b/src/frontend/src/content/docs/fundamentals/database-patterns.mdx @@ -1,5 +1,5 @@ --- -title: Aspire Database patterns +title: Aspire database patterns seoTitle: Learn strategies for using databases in Aspire solutions description: Learn about common patterns you can use to work with databases as you develop Aspire solutions. --- @@ -36,7 +36,7 @@ A database server, such as a PostgreSQL container, can host many databases. Your ### Create a database in the AppHost -The simplest way to create a database is to add a database resource to the server resource in your AppHost. Call on the server resource, then reference the database from the app that uses it: +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](https://www.nuget.org/packages/Aspire.Hosting.PostgreSQL) package. Call on the server resource, then reference the database from the app that uses it: @@ -207,7 +207,7 @@ const postgres = await builder.addPostgres('postgres'); const catalogdb = await postgres.addDatabase('catalogdb'); await builder.addNodeApp('api', './api', 'src/index.ts') - .withHttpEndpoint() + .withHttpEndpoint({ env: 'PORT' }) .withReference(catalogdb) .waitFor(catalogdb) .withHttpCommand('/admin/seed', 'Seed database', { @@ -247,6 +247,8 @@ builder.Build().Run(); +In the TypeScript example, `withHttpEndpoint({ env: 'PORT' })` passes the endpoint's 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. For a way to send a shared secret with each request, see [Considerations when registering HTTP commands](/fundamentals/http-commands/#considerations-when-registering-http-commands). @@ -372,7 +374,7 @@ builder.Build().Run(); If you prefer to apply EF Core migrations from your own code, create a worker service that calls `MigrateAsync` and exits. For a step-by-step guide, see [Create the migration service](/integrations/databases/efcore/migrations/#create-the-migration-service). -For Drizzle, 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 : +For Drizzle, 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 from the [📦 Aspire.Hosting.JavaScript](https://www.nuget.org/packages/Aspire.Hosting.JavaScript) package: ```json title="api/package.json" { @@ -393,7 +395,7 @@ const builder = await createBuilder(); const postgres = await builder.addPostgres('postgres'); const catalogdb = await postgres.addDatabase('catalogdb'); -const migrate = await builder.addJavaScriptApp('api-migrate', './api', 'db:migrate') +const migrate = await builder.addJavaScriptApp('api-migrate', './api', { runScriptName: 'db:migrate' }) .withReference(catalogdb) .waitFor(catalogdb); @@ -427,6 +429,8 @@ 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: ```typescript title="api/drizzle.config.ts" @@ -469,12 +473,18 @@ app.post('/admin/migrate', async (_req, res) => { res.json({ status: 'Migrations applied' }); }); -// Add your other routes, then start the server... +// Add your other routes... + +app.listen(process.env.PORT); ``` -With EF Core, the endpoint calls `MigrateAsync` on the database context: +With EF Core, 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](/integrations/databases/efcore/overview/#use-aspire-to-create-an-ef-core-context). ```csharp title="Program.cs" +using Microsoft.EntityFrameworkCore; + +// After you build the app... + app.MapPost("/admin/migrate", async (CatalogContext context) => { await context.Database.MigrateAsync(); @@ -496,7 +506,7 @@ const postgres = await builder.addPostgres('postgres'); const catalogdb = await postgres.addDatabase('catalogdb'); await builder.addNodeApp('api', './api', 'src/index.ts') - .withHttpEndpoint() + .withHttpEndpoint({ env: 'PORT' }) .withReference(catalogdb) .waitFor(catalogdb) .withHttpCommand('/admin/migrate', 'Apply migrations', { From ddad0ad8e585b1dc7bf8aba08326d7fabf745626 Mon Sep 17 00:00:00 2001 From: AJ Matthews Date: Thu, 22 Oct 2026 11:41:44 +0100 Subject: [PATCH 07/13] Fixed issues from @Copilot's review. --- .../docs/fundamentals/database-patterns.mdx | 65 +++++++++++++++---- 1 file changed, 52 insertions(+), 13 deletions(-) diff --git a/src/frontend/src/content/docs/fundamentals/database-patterns.mdx b/src/frontend/src/content/docs/fundamentals/database-patterns.mdx index 432cbd435c..08cdbfae37 100644 --- a/src/frontend/src/content/docs/fundamentals/database-patterns.mdx +++ b/src/frontend/src/content/docs/fundamentals/database-patterns.mdx @@ -179,7 +179,7 @@ With Drizzle, the `drizzle-seed` package generates realistic random data from yo ```typescript title="src/seed.ts" import { drizzle } from 'drizzle-orm/node-postgres'; import { seed } from 'drizzle-seed'; -import { products } from './schema'; +import { products } from './schema.ts'; export async function seedDatabase() { const db = drizzle(process.env.CATALOGDB_URI!); @@ -458,7 +458,9 @@ Applying migrations on every run isn't always what you want. For example, you mi 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. For more information, see [Automated EF migrations with `AddEFMigrations`](/integrations/databases/efcore/migrations/#automated-ef-migrations-with-addefmigrations). -For any ORM, you can also expose migrations as an endpoint in your app and call it with a custom HTTP command. With Drizzle, the endpoint calls the `migrate` function: +For any ORM, 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](/fundamentals/http-commands/#considerations-when-registering-http-commands). + +With Drizzle, the endpoint calls the `migrate` function: ```typescript title="api/src/index.ts" import express from 'express'; @@ -467,11 +469,19 @@ import { migrate } from 'drizzle-orm/node-postgres/migrator'; const app = express(); const db = drizzle(process.env.CATALOGDB_URI!); +const migrationKey = process.env.MIGRATION_KEY; -app.post('/admin/migrate', async (_req, res) => { - await migrate(db, { migrationsFolder: './drizzle' }); - res.json({ status: 'Migrations applied' }); -}); +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... @@ -481,27 +491,42 @@ app.listen(process.env.PORT); With EF Core, 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](/integrations/databases/efcore/overview/#use-aspire-to-create-an-ef-core-context). ```csharp title="Program.cs" +using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; // After you build the app... -app.MapPost("/admin/migrate", async (CatalogContext context) => +if (app.Environment.IsDevelopment()) { - await context.Database.MigrateAsync(); - return Results.Ok(new { status = "Migrations applied" }); -}); + 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: +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: ```typescript title="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'); @@ -509,9 +534,13 @@ 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(); @@ -521,21 +550,31 @@ await builder.build().run(); ```csharp title="AppHost.cs" +using System.Security.Cryptography; + var builder = DistributedApplication.CreateBuilder(args); +var migrationKey = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); + var postgres = builder.AddPostgres("postgres"); var catalogdb = postgres.AddDatabase("catalogdb"); builder.AddProject("api") .WithReference(catalogdb) .WaitFor(catalogdb) + .WithEnvironment("MIGRATION_KEY", migrationKey) .WithHttpCommand( path: "/admin/migrate", displayName: "Apply migrations", commandOptions: new HttpCommandOptions { Method = HttpMethod.Post, - ConfirmationMessage = "Apply pending migrations to the catalog database?" + ConfirmationMessage = "Apply pending migrations to the catalog database?", + PrepareRequest = context => + { + context.Request.Headers.Add("X-Migration-Key", migrationKey); + return Task.CompletedTask; + } }); builder.Build().Run(); @@ -622,7 +661,7 @@ When you deploy, the database resources in your AppHost become part of the deplo Your schema must also reach the deployed database. `RunDatabaseUpdateOnStart` affects only local runs, so plan a separate step for deployment: - With EF Core, publish your migrations as a container image with `PublishAsMigrationBundle`. The bundle runs as part of the deployment and applies pending migrations. For more information, see [Publish the migration bundle as a container image](/integrations/databases/efcore/migrations/#publish-the-migration-bundle-as-a-container-image). -- With Drizzle, the migration resource from [Apply schema migrations on startup](#apply-schema-migrations-on-startup) is deployed like any other app resource. Make sure it runs once and then stops, or call the `migrate` function when the app starts. Alternatively, run `drizzle-kit migrate` as a step in your CI/CD pipeline. +- With Drizzle, run `drizzle-kit migrate` as a step in your CI/CD pipeline, or call the `migrate` function when the deployed app starts. The migration resource from [Apply schema migrations on startup](#apply-schema-migrations-on-startup) configures a local run script; deploying it requires explicit runtime publishing configuration and a one-shot execution model for your deployment target. For publishing options, see [Deploy JavaScript apps](/deployment/javascript-apps/). 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. From 14fff457acf4d7195f0018c3574b7e077316dc2a Mon Sep 17 00:00:00 2001 From: AJ Matthews Date: Mon, 26 Oct 2026 14:42:19 +0000 Subject: [PATCH 08/13] Fixed two points of feedback from @IEvangelist. --- .../src/content/docs/fundamentals/database-patterns.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/frontend/src/content/docs/fundamentals/database-patterns.mdx b/src/frontend/src/content/docs/fundamentals/database-patterns.mdx index 08cdbfae37..a2b8b9fc02 100644 --- a/src/frontend/src/content/docs/fundamentals/database-patterns.mdx +++ b/src/frontend/src/content/docs/fundamentals/database-patterns.mdx @@ -18,7 +18,7 @@ Use this table to find the right approach for your requirements: | ----------------------- | --------------------------- | ------- | | Create a database | In the AppHost | [Add a database resource](#create-a-database-in-the-apphost) | | | In an orchestrated app | [On startup or with a custom command](#create-a-database-in-an-orchestrated-app) | -| | In a dashboard REPL terminal | [Run commands or a script](#create-a-database-in-a-dashboard-repl-terminal) | +| | In a dashboard REPL terminal | [Run commands or a script](#create-a-database-in-a-dashboard-repl-terminal) | | Seed a database | In an orchestrated app | [On startup or with a custom command](#seed-a-database-on-startup-or-using-a-custom-command) | | | | [Use EF Core or Drizzle migrations](#seed-a-database-using-orm-migrations) | | | In a dashboard REPL terminal | [Run a script](#seed-a-database-in-a-dashboard-repl-terminal) | @@ -645,7 +645,7 @@ builder.Build().Run(); In a C# AppHost, the persistent lifetime API is experimental and requires suppressing the [`ASPIREPERSISTENCE001`](/diagnostics/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. By default, Aspire generates a new server password on every run. Set the password as a secret or a parameter, so that the server can still open its existing data on the next run. +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. For more information, see [Persist Aspire data with volumes and binds](/fundamentals/persist-data-volumes/), [Create persistent passwords](/fundamentals/persist-data-volumes/#create-persistent-passwords), and [Container lifetime vs. data durability](/app-host/resource-lifetimes/#container-lifetime-vs-data-durability). From 740d77e8126198cc7d15d2197723f4169594bc20 Mon Sep 17 00:00:00 2001 From: AJ Matthews Date: Tue, 3 Nov 2026 12:08:00 +0000 Subject: [PATCH 09/13] Added a section about deployments that depend on successful migrations. --- .../docs/fundamentals/database-patterns.mdx | 443 +++++++++++++++++- 1 file changed, 442 insertions(+), 1 deletion(-) diff --git a/src/frontend/src/content/docs/fundamentals/database-patterns.mdx b/src/frontend/src/content/docs/fundamentals/database-patterns.mdx index a2b8b9fc02..3f86c15bae 100644 --- a/src/frontend/src/content/docs/fundamentals/database-patterns.mdx +++ b/src/frontend/src/content/docs/fundamentals/database-patterns.mdx @@ -660,7 +660,7 @@ When you deploy, the database resources in your AppHost become part of the deplo Your schema must also reach the deployed database. `RunDatabaseUpdateOnStart` affects only local runs, so plan a separate step for deployment: -- With EF Core, publish your migrations as a container image with `PublishAsMigrationBundle`. The bundle runs as part of the deployment and applies pending migrations. For more information, see [Publish the migration bundle as a container image](/integrations/databases/efcore/migrations/#publish-the-migration-bundle-as-a-container-image). +- With EF Core, publish your migrations as a container image with . The bundle is deployed with your app and applies pending migrations when it runs. On some targets, such as a manually triggered Azure Container Apps job, it doesn't run until you start it. For more information, see [Publish the migration bundle as a container image](/integrations/databases/efcore/migrations/#publish-the-migration-bundle-as-a-container-image) and [Ensure successful migrations deployment](#ensure-successful-migrations-deployment). - With Drizzle, run `drizzle-kit migrate` as a step in your CI/CD pipeline, or call the `migrate` function when the deployed app starts. The migration resource from [Apply schema migrations on startup](#apply-schema-migrations-on-startup) configures a local run script; deploying it requires explicit runtime publishing configuration and a one-shot execution model for your deployment target. For publishing options, see [Deploy JavaScript apps](/deployment/javascript-apps/). 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. @@ -669,6 +669,447 @@ Don't deploy development seed data or seed endpoints. Seed data that's part of y For more information, see [Deploy with Aspire](/deployment/deploy-with-aspire/), [Persistent volumes on Kubernetes](/deployment/kubernetes/persistent-volumes/), [Run as a local container during development](/integrations/cloud/azure/azure-postgresql/azure-postgresql-host/#run-as-a-local-container-during-development), and [Database creation after initial deployment](/integrations/cloud/azure/azure-postgresql/azure-postgresql-host/#database-creation-after-initial-deployment). +### Ensure successful migrations deployment + +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: + +- [Add a custom step to the Aspire deployment pipeline](#run-migrations-in-the-deployment-pipeline) so that `aspire deploy` runs a migration job and waits for it to succeed before it updates the app. +- [Run an EF Core migration bundle in your CI/CD pipeline](#run-a-migration-bundle-as-a-cicd-pre-deployment-step) before you call `aspire deploy`. + +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. + +#### Run migrations in the deployment pipeline + +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. +1. Starts the job and waits for it to finish. If the job fails, the step throws an error, and the pipeline stops. +1. 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. Aspire creates or updates each container app or job in a step named `provision--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. + +For EF Core, publish the migration bundle as a container image and deploy it as a manually triggered job with . Then add the custom step with `builder.Pipeline.AddStep` in C#, or `pipeline.addStep` in TypeScript: + + + + +```typescript title="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.addProject('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}.`); + } + } + }, { + // Run after the migration job is created or updated, + dependsOn: ['provision-api-migrations-containerapp'], + // and before the app is updated. + requiredBy: ['provision-api-containerapp'], + }); +} + +await builder.build().run(); +``` + + + + +```csharp title="AppHost.cs" +using System.Diagnostics; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +var builder = DistributedApplication.CreateBuilder(args); + +builder.AddAzureContainerAppEnvironment("env"); + +var postgres = builder.AddPostgres("postgres"); +var catalogdb = postgres.AddDatabase("catalogdb"); + +var api = builder.AddProject("api") + .WithReference(catalogdb); + +// Deploy the migration bundle as a manually triggered job. +api.AddEFMigrations("api-migrations") + .WithReference(catalogdb) + .WaitFor(catalogdb) + .PublishAsMigrationBundle(publishContainer: true) + .PublishAsAzureContainerAppJob(); + +if (builder.ExecutionContext.IsPublishMode) +{ +#pragma warning disable ASPIREPIPELINES001 + builder.Pipeline.AddStep("run-api-migrations", async context => + { + var config = context.Services.GetRequiredService(); + string[] job = ["--name", "api-migrations", "--resource-group", config["Azure:ResourceGroup"]!]; + + string[] startArgs = ["containerapp", "job", "start", .. job, "--query", "name", "--output", "tsv"]; + var execution = await RunAzAsync(startArgs, context.CancellationToken); + context.Logger.LogInformation("Started migration job execution {Execution}.", execution); + + string[] showArgs = + [ + "containerapp", "job", "execution", "show", .. job, + "--job-execution-name", execution, + "--query", "properties.status", "--output", "tsv" + ]; + + while (true) + { + await Task.Delay(TimeSpan.FromSeconds(10), context.CancellationToken); + var status = await RunAzAsync(showArgs, context.CancellationToken); + + if (status == "Succeeded") + { + context.Logger.LogInformation("Migrations applied."); + return; + } + + if (status is "Failed" or "Stopped" or "Degraded") + { + throw new InvalidOperationException( + $"Migration job execution {execution} ended with status {status}."); + } + } + }, + // Run after the migration job is created or updated, + dependsOn: "provision-api-migrations-containerapp", + // and before the app is updated. + requiredBy: "provision-api-containerapp"); +#pragma warning restore ASPIREPIPELINES001 +} + +builder.Build().Run(); + +static async Task RunAzAsync(string[] args, CancellationToken cancellationToken) +{ + var startInfo = new ProcessStartInfo("az") { RedirectStandardOutput = true }; + foreach (var arg in args) + { + startInfo.ArgumentList.Add(arg); + } + + using var process = Process.Start(startInfo)!; + var output = await process.StandardOutput.ReadToEndAsync(cancellationToken); + await process.WaitForExitAsync(cancellationToken); + + if (process.ExitCode != 0) + { + throw new InvalidOperationException($"'az {string.Join(' ', args)}' failed."); + } + + return output.Trim(); +} +``` + + + + +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`. In a C# AppHost, the pipeline API is experimental and requires suppressing the [`ASPIREPIPELINES001`](/diagnostics/aspirepipelines001/) diagnostic. + +For Drizzle, deploy the `db:migrate` script from [Apply schema migrations on startup](#apply-schema-migrations-on-startup) as a job. Call to build a container image that runs the script, and deploy the image as a manually triggered job. Then add the same custom step for the `api-migrate` job: + + + + +```typescript title="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}.`); + } + } + }, { + // Run after the migration job is created or updated, + dependsOn: ['provision-api-migrate-containerapp'], + // and before the app is updated. + requiredBy: ['provision-api-containerapp'], + }); +} + +await builder.build().run(); +``` + + + + +```csharp title="AppHost.cs" +using System.Diagnostics; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +var builder = DistributedApplication.CreateBuilder(args); + +builder.AddAzureContainerAppEnvironment("env"); + +var postgres = builder.AddPostgres("postgres"); +var catalogdb = postgres.AddDatabase("catalogdb"); + +// Deploy the db:migrate script as a manually triggered job. +#pragma warning disable ASPIREJAVASCRIPT001 +var migrate = builder.AddJavaScriptApp("api-migrate", "../api", "db:migrate") + .WithReference(catalogdb) + .WaitFor(catalogdb) + .PublishAsPackageScript(scriptName: "db:migrate") + .PublishAsAzureContainerAppJob(); +#pragma warning restore ASPIREJAVASCRIPT001 + +builder.AddNodeApp("api", "../api", "src/index.ts") + .WithReference(catalogdb) + .WaitForCompletion(migrate); + +if (builder.ExecutionContext.IsPublishMode) +{ +#pragma warning disable ASPIREPIPELINES001 + builder.Pipeline.AddStep("run-api-migrations", async context => + { + var config = context.Services.GetRequiredService(); + string[] job = ["--name", "api-migrate", "--resource-group", config["Azure:ResourceGroup"]!]; + + string[] startArgs = ["containerapp", "job", "start", .. job, "--query", "name", "--output", "tsv"]; + var execution = await RunAzAsync(startArgs, context.CancellationToken); + context.Logger.LogInformation("Started migration job execution {Execution}.", execution); + + string[] showArgs = + [ + "containerapp", "job", "execution", "show", .. job, + "--job-execution-name", execution, + "--query", "properties.status", "--output", "tsv" + ]; + + while (true) + { + await Task.Delay(TimeSpan.FromSeconds(10), context.CancellationToken); + var status = await RunAzAsync(showArgs, context.CancellationToken); + + if (status == "Succeeded") + { + context.Logger.LogInformation("Migrations applied."); + return; + } + + if (status is "Failed" or "Stopped" or "Degraded") + { + throw new InvalidOperationException( + $"Migration job execution {execution} ended with status {status}."); + } + } + }, + // Run after the migration job is created or updated, + dependsOn: "provision-api-migrate-containerapp", + // and before the app is updated. + requiredBy: "provision-api-containerapp"); +#pragma warning restore ASPIREPIPELINES001 +} + +builder.Build().Run(); + +static async Task RunAzAsync(string[] args, CancellationToken cancellationToken) +{ + var startInfo = new ProcessStartInfo("az") { RedirectStandardOutput = true }; + foreach (var arg in args) + { + startInfo.ArgumentList.Add(arg); + } + + using var process = Process.Start(startInfo)!; + var output = await process.StandardOutput.ReadToEndAsync(cancellationToken); + await process.WaitForExitAsync(cancellationToken); + + if (process.ExitCode != 0) + { + throw new InvalidOperationException($"'az {string.Join(' ', args)}' failed."); + } + + return output.Trim(); +} +``` + + + + +The container image includes only production dependencies, so list `drizzle-kit` under `dependencies` in _package.json_, not `devDependencies`. In a C# AppHost, the JavaScript publishing API is experimental and requires suppressing the [`ASPIREJAVASCRIPT001`](/diagnostics/aspirejavascript001/) diagnostic. + +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](/deployment/pipelines/), [Azure Container Apps jobs](/integrations/cloud/azure/container-app-jobs/), and [Jobs in Azure Container Apps](https://learn.microsoft.com/azure/container-apps/jobs) in the Azure documentation. + + +#### Run a migration bundle as a CI/CD pre-deployment step + +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. If it fails, the pipeline stops before `aspire deploy` runs. + +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: + + + + +```typescript title="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.addProject('api', '../Api/Api.csproj'); +await api.withReference(catalogdb); + +await api.addEFMigrations('api-migrations') + .publishAsMigrationBundle({ targetRuntime: 'linux-x64', selfContained: true }); + +await builder.build().run(); +``` + + + + +```csharp title="AppHost.cs" +var builder = DistributedApplication.CreateBuilder(args); + +var postgres = builder.AddPostgres("postgres"); +var catalogdb = postgres.AddDatabase("catalogdb"); + +var api = builder.AddProject("api") + .WithReference(catalogdb); + +api.AddEFMigrations("api-migrations") + .PublishAsMigrationBundle(targetRuntime: "linux-x64", selfContained: true); + +builder.Build().Run(); +``` + + + + +A pipeline step named `-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: + +```bash title="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. + +Drizzle has no equivalent of a bundle, but you can follow the same order. Run `npx drizzle-kit migrate` in your CI/CD pipeline with the production connection string, and then run `aspire deploy`. + + + For more information, see [Migration bundles](https://learn.microsoft.com/ef/core/managing-schemas/migrations/applying#bundles) in the EF Core documentation and the [`aspire do` command](/reference/cli/commands/aspire-do/). + + ## See also - [PostgreSQL integration](/integrations/databases/postgres/postgres-host/) From 12408101b0b27477355e2855599e961b2494f1bb Mon Sep 17 00:00:00 2001 From: AJ Matthews Date: Tue, 3 Nov 2026 14:53:39 +0000 Subject: [PATCH 10/13] Ran doc-tester and fixed the diagnosed problem. --- .../docs/fundamentals/database-patterns.mdx | 102 ++++++++++++++---- 1 file changed, 79 insertions(+), 23 deletions(-) diff --git a/src/frontend/src/content/docs/fundamentals/database-patterns.mdx b/src/frontend/src/content/docs/fundamentals/database-patterns.mdx index 3f86c15bae..6e095ed971 100644 --- a/src/frontend/src/content/docs/fundamentals/database-patterns.mdx +++ b/src/frontend/src/content/docs/fundamentals/database-patterns.mdx @@ -686,9 +686,11 @@ The `aspire deploy` command runs a pipeline of named steps, such as `provision-a 1. Starts the job and waits for it to finish. If the job fails, the step throws an error, and the pipeline stops. 1. 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. Aspire creates or updates each container app or job in a step named `provision--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. +The following examples deploy to Azure Container Apps, so they need the [📦 Aspire.Hosting.Azure.AppContainers](https://www.nuget.org/packages/Aspire.Hosting.Azure.AppContainers) package. Aspire creates or updates each container app or job in a step named `provision--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. -For EF Core, publish the migration bundle as a container image and deploy it as a manually triggered job with . Then add the custom step with `builder.Pipeline.AddStep` in C#, or `pipeline.addStep` in TypeScript: +Aspire creates the Azure deployment steps while it resolves the pipeline, after your AppHost code adds its own steps. If you name an Azure step in the `dependsOn` or `requiredBy` options of a new step, the pipeline fails with an `unknown step` error. Instead, add the 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. + +For EF Core, publish the migration bundle as a container image and deploy it as a manually triggered job with . 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`: @@ -751,11 +753,23 @@ if (await builder.executionContext().isPublishMode()) { throw new Error(`Migration job execution ${execution} ended with status ${status}.`); } } - }, { - // Run after the migration job is created or updated, - dependsOn: ['provision-api-migrations-containerapp'], - // and before the app is updated. - requiredBy: ['provision-api-containerapp'], + }); + + // 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'); + } }); } @@ -824,11 +838,26 @@ if (builder.ExecutionContext.IsPublishMode) $"Migration job execution {execution} ended with status {status}."); } } - }, - // Run after the migration job is created or updated, - dependsOn: "provision-api-migrations-containerapp", - // and before the app is updated. - requiredBy: "provision-api-containerapp"); + }); + + // Azure creates its deployment steps while the pipeline resolves, + // so add the dependencies in a configuration callback. + builder.Pipeline.AddPipelineConfiguration(context => + { + var runMigrations = context.Steps.Single(s => s.Name == "run-api-migrations"); + var deployJob = context.Steps.SingleOrDefault(s => s.Name == "provision-api-migrations-containerapp"); + var deployApp = context.Steps.SingleOrDefault(s => s.Name == "provision-api-containerapp"); + + if (deployJob is not null && deployApp is not null) + { + // Run after the migration job is created or updated, + runMigrations.DependsOn(deployJob); + // and before the app is updated. + deployApp.DependsOn(runMigrations); + } + + return Task.CompletedTask; + }); #pragma warning restore ASPIREPIPELINES001 } @@ -860,7 +889,7 @@ static async Task RunAzAsync(string[] args, CancellationToken cancellati 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`. In a C# AppHost, the pipeline API is experimental and requires suppressing the [`ASPIREPIPELINES001`](/diagnostics/aspirepipelines001/) diagnostic. -For Drizzle, deploy the `db:migrate` script from [Apply schema migrations on startup](#apply-schema-migrations-on-startup) as a job. Call to build a container image that runs the script, and deploy the image as a manually triggered job. Then add the same custom step for the `api-migrate` job: +For Drizzle, deploy the `db:migrate` script from [Apply schema migrations on startup](#apply-schema-migrations-on-startup) as a job. Call to build a container image that runs the script, and deploy the image as a manually triggered job. Then add the same custom step and configuration callback for the `api-migrate` job: @@ -924,11 +953,23 @@ if (await builder.executionContext().isPublishMode()) { throw new Error(`Migration job execution ${execution} ended with status ${status}.`); } } - }, { - // Run after the migration job is created or updated, - dependsOn: ['provision-api-migrate-containerapp'], - // and before the app is updated. - requiredBy: ['provision-api-containerapp'], + }); + + // 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'); + } }); } @@ -1000,11 +1041,26 @@ if (builder.ExecutionContext.IsPublishMode) $"Migration job execution {execution} ended with status {status}."); } } - }, - // Run after the migration job is created or updated, - dependsOn: "provision-api-migrate-containerapp", - // and before the app is updated. - requiredBy: "provision-api-containerapp"); + }); + + // Azure creates its deployment steps while the pipeline resolves, + // so add the dependencies in a configuration callback. + builder.Pipeline.AddPipelineConfiguration(context => + { + var runMigrations = context.Steps.Single(s => s.Name == "run-api-migrations"); + var deployJob = context.Steps.SingleOrDefault(s => s.Name == "provision-api-migrate-containerapp"); + var deployApp = context.Steps.SingleOrDefault(s => s.Name == "provision-api-containerapp"); + + if (deployJob is not null && deployApp is not null) + { + // Run after the migration job is created or updated, + runMigrations.DependsOn(deployJob); + // and before the app is updated. + deployApp.DependsOn(runMigrations); + } + + return Task.CompletedTask; + }); #pragma warning restore ASPIREPIPELINES001 } From c41b301495653932a805ae64ed22a3caaef230c4 Mon Sep 17 00:00:00 2001 From: AJ Matthews Date: Mon, 23 Nov 2026 16:17:16 +0000 Subject: [PATCH 11/13] Moved EF Core samples and other patterns from other documents into the database patterns document. --- .../docs/app-host/resource-lifetimes.mdx | 2 +- .../fundamentals/custom-resource-commands.mdx | 4 +- .../docs/fundamentals/database-patterns.mdx | 515 +++++++++++++++++- .../docs/fundamentals/http-commands.mdx | 2 +- .../fundamentals/persist-data-volumes.mdx | 1 + .../databases/efcore/migrations.mdx | 9 +- .../databases/efcore/overview.mdx | 3 +- .../databases/efcore/seed-database.mdx | 219 +------- .../databases/mongodb/mongodb-host.mdx | 16 + .../databases/mysql/mysql-host.mdx | 20 + .../databases/postgres/postgres-host.mdx | 20 + .../databases/sql-server/sql-server-host.mdx | 16 + 12 files changed, 586 insertions(+), 241 deletions(-) diff --git a/src/frontend/src/content/docs/app-host/resource-lifetimes.mdx b/src/frontend/src/content/docs/app-host/resource-lifetimes.mdx index 1cb9599393..a73dab002e 100644 --- a/src/frontend/src/content/docs/app-host/resource-lifetimes.mdx +++ b/src/frontend/src/content/docs/app-host/resource-lifetimes.mdx @@ -512,5 +512,5 @@ await postgres.withDataVolume(); For **caches or other ephemeral state**, `WithPersistentLifetime()` alone may be sufficient because losing data on container recreation is acceptable. :::tip -For more details on volumes and bind mounts, see [Persist data using volumes](/fundamentals/persist-data-volumes/). +For more details on volumes and bind mounts, see [Persist data using volumes](/fundamentals/persist-data-volumes/). For how persistence affects database seed data and initialization scripts, see [Persist a database across restarts](/fundamentals/database-patterns/#persist-a-database-across-restarts). ::: diff --git a/src/frontend/src/content/docs/fundamentals/custom-resource-commands.mdx b/src/frontend/src/content/docs/fundamentals/custom-resource-commands.mdx index ae4daba429..0bf46d82b1 100644 --- a/src/frontend/src/content/docs/fundamentals/custom-resource-commands.mdx +++ b/src/frontend/src/content/docs/fundamentals/custom-resource-commands.mdx @@ -12,7 +12,7 @@ import customClearCacheCommandSucceeded from '@assets/fundamentals/custom-clear- import customClearCacheCommandSucceededLight from '@assets/fundamentals/custom-clear-cache-command-succeeded-light.png'; import ApiReference from '@components/ApiReference.astro'; -Each resource in the Aspire app model is represented as an `IResource` and when added to the distributed application builder, it's the generic-type parameter of the `IResourceBuilder` interface. You use the _resource builder_ API to chain calls, configuring the underlying resource, and in some situations, you might want to add custom commands to the resource. Some common scenario for creating a custom command might be running database migrations or seeding/resetting a database. In this article, you learn how to add a custom command to a Redis resource that clears the cache. +Each resource in the Aspire app model is represented as an `IResource` and when added to the distributed application builder, it's the generic-type parameter of the `IResourceBuilder` interface. You use the _resource builder_ API to chain calls, configuring the underlying resource, and in some situations, you might want to add custom commands to the resource. Some common scenario for creating a custom command might be running database migrations or seeding/resetting a database. For database examples, see [Aspire database patterns](/fundamentals/database-patterns/). In this article, you learn how to add a custom command to a Redis resource that clears the cache. + + For how persistence affects seed data and initialization scripts, see [Persist a database across restarts](/fundamentals/database-patterns/#persist-a-database-across-restarts). + + ## Add MongoDB server resource with data bind mount To add a data bind mount to the MongoDB server resource, call the method: @@ -575,6 +579,10 @@ Data [bind mounts](https://docs.docker.com/engine/storage/bind-mounts/) have lim Data bind mounts rely on the host machine's filesystem to persist the MongoDB server data across container restarts. The data bind mount is mounted at the `C:\MongoDB\Data` on Windows (or `/MongoDB/Data` on Unix) path on the host machine in the MongoDB server container. For more information on data bind mounts, see [Docker docs: Bind mounts](https://docs.docker.com/engine/storage/bind-mounts). + + For how persistence affects seed data and initialization scripts, see [Persist a database across restarts](/fundamentals/database-patterns/#persist-a-database-across-restarts). + + ## Add MongoDB server resource with init files Use initialization files to seed the MongoDB server with data or run scripts at startup. Call `WithInitFiles(...)` in a C# AppHost or `withInitFiles(...)` in a TypeScript AppHost to copy the files from the specified directory into the container's initialization folder. @@ -640,6 +648,10 @@ builder.AddGoApp("api", "./api"). MongoDB executes any JavaScript or shell scripts found in the init folder when the container first starts. This is useful for pre-populating collections or creating indexes. + + For other ways to seed a database, see [Seed a database with sample data](/fundamentals/database-patterns/#seed-a-database-with-sample-data). + + ## Enable transactions and change streams with a single-member replica set MongoDB transactions and change streams require replica-set mode, even for a single server. Call `WithReplicaSet` (C#) or `withReplicaSet` (TypeScript) directly on the `MongoDBServerResource` to configure **and initialize** a single-member replica set, without creating a separate logical replica-set resource or configuring split-horizon TLS. Continue using , , and as usual — initialization runs during the resource lifecycle, and readiness waits for both initialization and primary election, so consumers can use transactions and change streams as soon as `WaitFor` completes. @@ -1048,6 +1060,10 @@ Use `exit` before closing the terminal tab. Closing the tab alone can leave the The client uses the resource's configured credentials and can modify or delete data. Enable it only for trusted dashboard users, including anyone accessing the dashboard through a tunnel or remote development session. ::: + + For examples that use the REPL to create, seed, or change a database, see [Aspire database patterns](/fundamentals/database-patterns/). + + ## Connection properties For the full reference of MongoDB connection properties — and how consuming apps in C#, TypeScript, Python, and Go read them — see [Connect to MongoDB](../mongodb-connect/). diff --git a/src/frontend/src/content/docs/integrations/databases/mysql/mysql-host.mdx b/src/frontend/src/content/docs/integrations/databases/mysql/mysql-host.mdx index 2778ce5b18..12a1f8fbb8 100644 --- a/src/frontend/src/content/docs/integrations/databases/mysql/mysql-host.mdx +++ b/src/frontend/src/content/docs/integrations/databases/mysql/mysql-host.mdx @@ -264,6 +264,10 @@ builder.AddGoApp("api", "./api"). The script is executed only when the database is first created. If you need to run scripts on every startup, consider using init files or application-level migrations instead. + + For other ways to create a database, see [Create a database](/fundamentals/database-patterns/#create-a-database). + + ## Add MySQL resource with phpMyAdmin [**phpMyAdmin**](https://www.phpmyadmin.net/) is a popular web-based administration tool for MySQL. Call the method to add a phpMyAdmin container resource that connects to the MySQL container: @@ -468,6 +472,10 @@ Some database integrations, including the MySQL integration, can't successfully You can resolve the problem by deploying to a Kubernetes cluster, such as Azure Kubernetes Services (AKS). For more information, see [Deploy your first Aspire app](/get-started/deploy-first-app/). + + For how persistence affects seed data and initialization scripts, see [Persist a database across restarts](/fundamentals/database-patterns/#persist-a-database-across-restarts). + + ## Add a MySQL resource with a data bind mount Add a data bind mount to the MySQL server resource as shown in the following examples: @@ -536,6 +544,10 @@ builder.AddGoApp("api", "./api"). Data bind mounts rely on the host machine's filesystem to persist the MySQL server data across container restarts. The data bind mount is mounted at the `C:\MySQL\Data` on Windows (or `/MySQL/Data` on Unix) path on the host machine in the MySQL server container. For more information on data bind mounts, see [Docker docs: Bind mounts](https://docs.docker.com/engine/storage/bind-mounts). + + For how persistence affects seed data and initialization scripts, see [Persist a database across restarts](/fundamentals/database-patterns/#persist-a-database-across-restarts). + + ## Add MySQL resource with init files Use initialization files to seed or configure the MySQL server at startup. Call `WithInitFiles(...)` in a C# AppHost or `withInitFiles(...)` in a TypeScript AppHost to copy the files from the specified directory into the container's initialization folder. @@ -598,6 +610,10 @@ builder.AddGoApp("api", "./api"). The init files are executed when the MySQL server container starts. Place executable shell scripts or `.sql` files in the directory to initialize the database schema, seed data, or perform other setup tasks. + + For other ways to seed a database, see [Seed a database with sample data](/fundamentals/database-patterns/#seed-a-database-with-sample-data). + + ## Add MySQL resource with parameters When you want to provide a root MySQL password and optional port explicitly, you can pass them as parameters: @@ -799,6 +815,10 @@ Use `quit` before closing the terminal tab. Closing the tab alone can leave the The client uses the resource's configured credentials and can modify or delete data. Enable it only for trusted dashboard users, including anyone accessing the dashboard through a tunnel or remote development session. ::: + + For examples that use the REPL to create, seed, or change a database, see [Aspire database patterns](/fundamentals/database-patterns/). + + ## Connection properties For the full reference of MySQL connection properties — and how consuming apps in C#, TypeScript, Python, and Go read them — see [Connect to MySQL](../mysql-connect/). diff --git a/src/frontend/src/content/docs/integrations/databases/postgres/postgres-host.mdx b/src/frontend/src/content/docs/integrations/databases/postgres/postgres-host.mdx index 9149929580..bc4203caae 100644 --- a/src/frontend/src/content/docs/integrations/databases/postgres/postgres-host.mdx +++ b/src/frontend/src/content/docs/integrations/databases/postgres/postgres-host.mdx @@ -254,6 +254,10 @@ The preceding example creates a database named `app_db`. The script is run when The connect to a database command (`\c`) isn't supported when using the creation script. + + For other ways to create a database, see [Create a database](/fundamentals/database-patterns/#create-a-database). + + ## Add PostgreSQL pgAdmin resource Add the [**dpage/pgadmin4**](https://www.pgadmin.org/) container to the PostgreSQL resource to get a web-based admin dashboard, as shown in the following examples: @@ -577,6 +581,10 @@ The data volume is used to persist the PostgreSQL server data outside the lifecy You can resolve the problem by using the managed service **Azure Database for PostgreSQL** to host the deployed database instead of a container in ACA, which is the recommended approach regardless of this issue. For that managed-service flow, see [Azure Database for PostgreSQL Hosting integration](/integrations/cloud/azure/azure-postgresql/azure-postgresql-host/). + + For how persistence affects seed data and initialization scripts, see [Persist a database across restarts](/fundamentals/database-patterns/#persist-a-database-across-restarts). + + ## Add PostgreSQL server resource with data bind mount Add a data bind mount to the PostgreSQL server resource as shown in the following examples: @@ -642,6 +650,10 @@ builder.AddGoApp("api", "./api"). Data bind mounts rely on the host machine's filesystem to persist the PostgreSQL server data across container restarts. The data bind mount is mounted at the `C:\PostgreSQL\Data` on Windows (or `/PostgreSQL/Data` on Unix) path on the host machine in the PostgreSQL server container. For more information on data bind mounts, see [Docker docs: Bind mounts](https://docs.docker.com/engine/storage/bind-mounts). + + For how persistence affects seed data and initialization scripts, see [Persist a database across restarts](/fundamentals/database-patterns/#persist-a-database-across-restarts). + + ## Add PostgreSQL server resource with init files Use initialization files to seed the PostgreSQL server. Call `WithInitFiles(...)` in a C# AppHost or `withInitFiles(...)` in a TypeScript AppHost to copy the files from the specified directory into the container's initialization folder. @@ -704,6 +716,10 @@ The Go AppHost doesn't expose the obsolete bind-mount API for PostgreSQL initial The files in the specified directory are copied into the PostgreSQL server container's _init_ folder. This folder is used for initialization, running any executable shell scripts or _.sql_ command files after the _postgres-data_ folder is created. + + For an example initialization script that creates and seeds a database, see [Seed a database in a dashboard REPL terminal](/fundamentals/database-patterns/#seed-a-database-in-a-dashboard-repl-terminal). For other ways to seed a database, see [Seed a database with sample data](/fundamentals/database-patterns/#seed-a-database-with-sample-data). + + ## Add PostgreSQL server resource with parameters When you want to explicitly provide the username and password used by the container image, you can provide these credentials as parameters. Consider the following alternative examples: @@ -980,6 +996,10 @@ Use `\connect` to switch databases and `\q` to exit before closing the terminal The client uses the resource's configured credentials and can modify or delete data. Enable it only for trusted dashboard users, including anyone accessing the dashboard through a tunnel or remote development session. ::: + + For examples that use the REPL to create, seed, or change a database, see [Aspire database patterns](/fundamentals/database-patterns/). + + ## Connection properties For the full reference of PostgreSQL connection properties — and how consuming apps in C#, TypeScript, Python, and Go read them — see [Connect to PostgreSQL](../postgres-connect/). diff --git a/src/frontend/src/content/docs/integrations/databases/sql-server/sql-server-host.mdx b/src/frontend/src/content/docs/integrations/databases/sql-server/sql-server-host.mdx index 25d793da9c..d4365ed0dd 100644 --- a/src/frontend/src/content/docs/integrations/databases/sql-server/sql-server-host.mdx +++ b/src/frontend/src/content/docs/integrations/databases/sql-server/sql-server-host.mdx @@ -320,6 +320,10 @@ if err := app.Run(); err != nil { The preceding example creates a database named `app-db` with a single `todos` table. The script is executed when the database resource is created in the context of the SQL Server resource. + + For other ways to create a database, see [Create a database](/fundamentals/database-patterns/#create-a-database). + + ## Add SQL Server resource with data volume Add a data volume to the SQL Server resource as shown in the following examples: @@ -395,6 +399,10 @@ The data volume is used to persist the SQL Server data outside the lifecycle of The password is stored in the data volume. When using a data volume and if the password changes, it will not work until you delete the volume. + + For how persistence affects seed data and initialization scripts, see [Persist a database across restarts](/fundamentals/database-patterns/#persist-a-database-across-restarts). + + ## Add SQL Server resource with data bind mount Add a data bind mount to the SQL Server resource as shown in the following examples: @@ -470,6 +478,10 @@ if err := app.Run(); err != nil { Data bind mounts rely on the host machine's filesystem to persist the SQL Server data across container restarts. The data bind mount is mounted at the `C:\SqlServer\Data` on Windows (or `/SqlServer/Data` on Unix) path on the host machine in the SQL Server container. For more information on data bind mounts, see [Docker docs: Bind mounts](https://docs.docker.com/engine/storage/bind-mounts). + + For how persistence affects seed data and initialization scripts, see [Persist a database across restarts](/fundamentals/database-patterns/#persist-a-database-across-restarts). + + ## Add SQL Server resource with parameters When you want to explicitly provide the password used by the container image, you can provide it as a parameter: @@ -870,6 +882,10 @@ Use `USE [db];` followed by `GO` to switch databases, and `QUIT` to exit before The client runs as `sa`, can modify or delete data, and can execute server-side operating system commands when enabled. Enable it only for trusted dashboard users, including anyone accessing the dashboard through a tunnel or remote development session. ::: + + For examples that use the REPL to create, seed, or change a database, see [Aspire database patterns](/fundamentals/database-patterns/). + + ### Select the client executable :::note[Breaking change] From 5e6efce362b656020c47ce47565cf9f3b0bf7e48 Mon Sep 17 00:00:00 2001 From: AJ Matthews Date: Mon, 23 Nov 2026 16:44:42 +0000 Subject: [PATCH 12/13] Implemented a pivot on the ORM technology. --- .../docs/fundamentals/database-patterns.mdx | 562 +++++++++++++++--- .../databases/efcore/migrations.mdx | 10 +- .../databases/efcore/overview.mdx | 4 +- .../databases/efcore/seed-database.mdx | 10 +- 4 files changed, 499 insertions(+), 87 deletions(-) diff --git a/src/frontend/src/content/docs/fundamentals/database-patterns.mdx b/src/frontend/src/content/docs/fundamentals/database-patterns.mdx index d1efe97f7d..3aa61fb02e 100644 --- a/src/frontend/src/content/docs/fundamentals/database-patterns.mdx +++ b/src/frontend/src/content/docs/fundamentals/database-patterns.mdx @@ -7,10 +7,21 @@ description: Learn about common patterns you can use to work with databases as y import { Tabs, TabItem } from '@astrojs/starlight/components'; import LearnMore from '@components/LearnMore.astro'; import ApiReference from '@components/ApiReference.astro'; +import PivotSelector from '@components/PivotSelector.astro'; +import Pivot from '@components/Pivot.astro'; 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 shows both Entity Framework Core (EF Core) for .NET apps and Drizzle for JavaScript and TypeScript apps. +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: + + Use this table to find the right approach for your requirements: @@ -87,6 +98,8 @@ To control how the database is created, for example to set a collation or an own 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`: @@ -119,6 +132,10 @@ if (app.Environment.IsDevelopment()) 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: ```typescript title="src/create-database.ts" @@ -139,6 +156,8 @@ 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](#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](/integrations/databases/postgres/postgres-connect/). @@ -202,7 +221,9 @@ When your app seeds the database, the seed logic lives in source control next to 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. -With EF Core, 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: + + +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: ```csharp title="Program.cs" using Microsoft.EntityFrameworkCore; @@ -253,7 +274,11 @@ app.Run(); To register the `DbContext` for SQL Server or MySQL instead, see [Seed data using EF Core](/integrations/databases/efcore/seed-database/#seed-data-using-ef-core). -With Drizzle, the `drizzle-seed` package generates realistic random data from your schema. The following example seeds the `products` table only when it's empty: + + + + +The `drizzle-seed` package generates realistic random data from your schema. The following example seeds the `products` table only when it's empty: ```typescript title="src/seed.ts" import { drizzle } from 'drizzle-orm/node-postgres'; @@ -272,29 +297,13 @@ export async function seedDatabase() { 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. - -With Drizzle, the endpoint calls the `seedDatabase` function from the previous example: - -```typescript title="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... +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. -app.listen(process.env.PORT); -``` + -With EF Core, the endpoint adds the rows through the database context. It checks for existing rows first, so you can run the command more than once: +The endpoint adds the rows through the database context. It checks for existing rows first, so you can run the command more than once: ```csharp title="Program.cs" using Microsoft.EntityFrameworkCore; @@ -329,6 +338,83 @@ 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(); +``` + + + + +```csharp title="AppHost.cs" +var builder = DistributedApplication.CreateBuilder(args); + +var postgres = builder.AddPostgres("postgres"); +var catalogdb = postgres.AddDatabase("catalogdb"); + +builder.AddDotnetProject("api", "../Api/Api.csproj") + .WithReference(catalogdb) + .WaitFor(catalogdb) + .WithHttpCommand( + path: "/admin/seed", + displayName: "Seed database", + commandOptions: new HttpCommandOptions + { + Method = HttpMethod.Post, + Description = "Adds sample data to the catalog database.", + ConfirmationMessage = "Add sample data to the catalog database?" + }); + +builder.Build().Run(); +``` + + + + + + + + +The endpoint calls the `seedDatabase` function from the previous example: + +```typescript title="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 : + + + + +```typescript title="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) @@ -351,7 +437,8 @@ var builder = DistributedApplication.CreateBuilder(args); var postgres = builder.AddPostgres("postgres"); var catalogdb = postgres.AddDatabase("catalogdb"); -builder.AddDotnetProject("api", "../Api/Api.csproj") +builder.AddNodeApp("api", "../api", "src/index.ts") + .WithHttpEndpoint(env: "PORT") .WithReference(catalogdb) .WaitFor(catalogdb) .WithHttpCommand( @@ -370,7 +457,9 @@ builder.Build().Run(); -In the TypeScript example, `withHttpEndpoint({ env: 'PORT' })` passes the endpoint's port to the app in the `PORT` environment variable. The app must listen on `process.env.PORT`, otherwise the command can't reach it. +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](#modify-a-schema-with-a-custom-command) show how to send a shared secret with each request. @@ -382,7 +471,9 @@ Protect seed endpoints so that only the AppHost can call them, and don't expose 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. -With EF Core, call `HasData` in `OnModelCreating` to define seed rows as part of your model. Each row needs a primary key value: + + +Call `HasData` in `OnModelCreating` to define seed rows as part of your model. Each row needs a primary key value: ```csharp title="CatalogContext.cs" protected override void OnModelCreating(ModelBuilder modelBuilder) @@ -402,7 +493,11 @@ 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](https://learn.microsoft.com/ef/core/modeling/data-seeding#model-managed-data) in the EF Core documentation. -With Drizzle, generate an empty custom migration: + + + + +Generate an empty custom migration: ```bash title="Terminal" npx drizzle-kit generate --custom --name=seed-order-statuses @@ -419,6 +514,8 @@ INSERT INTO order_statuses (id, name) VALUES 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](https://orm.drizzle.team/docs/kit-custom-migrations) in the Drizzle documentation. + + To learn how to apply migrations when your app runs, see [Modify a database schema](#modify-a-database-schema). ### Seed a database in a dashboard REPL terminal @@ -481,7 +578,56 @@ When Aspire later creates `catalogdb`, it finds the database and leaves it in pl PostgreSQL runs these scripts only when it initializes an empty data directory. If you [persist the database](#persist-a-database-across-restarts) with a data volume, the scripts don't run again until you remove the volume. -To run a seed program written in another language, such as a Node.js or Python script, add it to the AppHost as a resource that you start from the dashboard. Call so that the resource doesn't run with the rest of the app. The resource receives the database's connection information from `WithReference`, in the same way as the app. This example runs a `db:seed` script from the app's _package.json_ file: +To run a separate seed program, add it to the AppHost as a resource that you start from the dashboard. Call so that the resource doesn't run with the rest of the app. The resource receives the database's connection information from `WithReference`, 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: + + + + +```typescript title="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(); +``` + + + + +```csharp title="AppHost.cs" +var builder = DistributedApplication.CreateBuilder(args); + +var postgres = builder.AddPostgres("postgres"); +var catalogdb = postgres.AddDatabase("catalogdb"); + +builder.AddDotnetProject("api-seed", "../SeedData/SeedData.csproj") + .WithReference(catalogdb) + .WaitFor(catalogdb) + .WithExplicitStart(); + +builder.Build().Run(); +``` + + + + + + + + +This example runs a `db:seed` script from the app's _package.json_ file: @@ -522,6 +668,8 @@ 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](/fundamentals/custom-resource-commands/#process-backed-resource-commands). @@ -530,16 +678,27 @@ To seed, select **Start** on the `api-seed` resource in the dashboard. The resou ## Modify a database schema -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. Both EF Core and Drizzle generate migrations from changes to your model: +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 ` to generate a C# migration from changes to your `DbContext` model. For more information, see [Create migrations](/integrations/databases/efcore/migrations/#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](https://orm.drizzle.team/docs/migrations) in the Drizzle documentation. -- With EF Core, run `dotnet ef migrations add ` to generate a C# migration from changes to your `DbContext` model. For more information, see [Create migrations](/integrations/databases/efcore/migrations/#create-migrations). -- With Drizzle, run `npx drizzle-kit generate` to generate a SQL migration from changes to your schema file. For more information, see [Migrations with Drizzle](https://orm.drizzle.team/docs/migrations) in the Drizzle documentation. + ### Apply schema migrations on startup To keep the database schema in step with your code, apply pending migrations every time the app runs. -For EF Core, add a migration resource to your AppHost with from the [📦 Aspire.Hosting.EntityFrameworkCore](https://www.nuget.org/packages/Aspire.Hosting.EntityFrameworkCore) package. This package is in preview. Call to apply migrations when the AppHost starts, and make the app wait for the migrations to finish with : + + +Add a migration resource to your AppHost with from the [📦 Aspire.Hosting.EntityFrameworkCore](https://www.nuget.org/packages/Aspire.Hosting.EntityFrameworkCore) package. This package is in preview. Call to apply migrations when the AppHost starts, and make the app wait for the migrations to finish with : @@ -669,7 +828,11 @@ builder.Build().Run(); If the migrations fail, the worker exits with an error and the app doesn't start. For a step-by-step tutorial that builds a migration service, see [Apply EF Core migrations in Aspire](/integrations/databases/efcore/migrations/#create-the-migration-service). -For Drizzle, 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 from the [📦 Aspire.Hosting.JavaScript](https://www.nuget.org/packages/Aspire.Hosting.JavaScript) package: + + + + +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 from the [📦 Aspire.Hosting.JavaScript](https://www.nuget.org/packages/Aspire.Hosting.JavaScript) package: ```json title="api/package.json" { @@ -763,13 +926,21 @@ 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](/integrations/frameworks/javascript/#customize-scripts). For more information about waiting for resources, see [Health checks](/fundamentals/health-checks/). + For more information about the JavaScript hosting APIs, see [Customize scripts](/integrations/frameworks/javascript/#customize-scripts). + + + + + + For more information about waiting for resources, see [Health checks](/fundamentals/health-checks/). ### Modify a schema with a custom command 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 : @@ -817,9 +988,109 @@ 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`](/integrations/databases/efcore/migrations/#automated-ef-migrations-with-addefmigrations). -For any ORM, 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](/fundamentals/http-commands/#considerations-when-registering-http-commands). +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](/fundamentals/http-commands/#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](/integrations/databases/efcore/overview/#use-aspire-to-create-an-ef-core-context). + +```csharp title="Program.cs" +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; -With Drizzle, the endpoint calls the `migrate` function: +// 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: + + + + +```typescript title="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(); +``` + + + + +```csharp title="AppHost.cs" +using System.Security.Cryptography; + +var builder = DistributedApplication.CreateBuilder(args); + +var migrationKey = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); + +var postgres = builder.AddPostgres("postgres"); +var catalogdb = postgres.AddDatabase("catalogdb"); + +builder.AddDotnetProject("api", "../Api/Api.csproj") + .WithReference(catalogdb) + .WaitFor(catalogdb) + .WithEnvironment("MIGRATION_KEY", migrationKey) + .WithHttpCommand( + path: "/admin/migrate", + displayName: "Apply migrations", + commandOptions: new HttpCommandOptions + { + Method = HttpMethod.Post, + ConfirmationMessage = "Apply pending migrations to the catalog database?", + PrepareRequest = context => + { + context.Request.Headers.Add("X-Migration-Key", migrationKey); + return Task.CompletedTask; + } + }); + +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](/fundamentals/http-commands/#considerations-when-registering-http-commands). + +The endpoint calls the `migrate` function: ```typescript title="api/src/index.ts" import express from 'express'; @@ -847,32 +1118,6 @@ if (process.env.NODE_ENV === 'development' && migrationKey) { app.listen(process.env.PORT); ``` -With EF Core, 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](/integrations/databases/efcore/overview/#use-aspire-to-create-an-ef-core-context). - -```csharp title="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: @@ -918,7 +1163,8 @@ var migrationKey = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); var postgres = builder.AddPostgres("postgres"); var catalogdb = postgres.AddDatabase("catalogdb"); -builder.AddDotnetProject("api", "../Api/Api.csproj") +builder.AddNodeApp("api", "../api", "src/index.ts") + .WithHttpEndpoint(env: "PORT") .WithReference(catalogdb) .WaitFor(catalogdb) .WithEnvironment("MIGRATION_KEY", migrationKey) @@ -942,6 +1188,10 @@ 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](#deploy-a-database-with-an-aspire-solution). @@ -1019,6 +1269,8 @@ When you deploy, the database resources in your AppHost become part of the deplo 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](https://www.nuget.org/packages/Aspire.Hosting.Azure.PostgreSQL) package: + + @@ -1032,7 +1284,7 @@ await postgres.runAsContainer(); const catalogdb = await postgres.addDatabase('catalogdb'); -await builder.addNodeApp('api', './api', 'src/index.ts') +await builder.addDotnetProject('api', '../Api/Api.csproj') .withReference(catalogdb) .waitFor(catalogdb); @@ -1060,12 +1312,60 @@ builder.Build().Run(); + + + + + + + +```typescript title="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(); +``` + + + + +```csharp title="AppHost.cs" +var builder = DistributedApplication.CreateBuilder(args); + +var postgres = builder.AddAzurePostgresFlexibleServer("postgres") + .RunAsContainer(); + +var catalogdb = postgres.AddDatabase("catalogdb"); + +builder.AddNodeApp("api", "../api", "src/index.ts") + .WithReference(catalogdb) + .WaitFor(catalogdb); + +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. `RunDatabaseUpdateOnStart` affects only local runs, so plan a separate step for deployment: +Your schema must also reach the deployed database, so plan how your migrations run when you deploy. -- With EF Core, publish your migrations as a container image with . 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 instead. It generates an idempotent SQL script during `aspire publish`, which you then run against the database yourself. -- With Drizzle, run `drizzle-kit migrate` as a step in your CI/CD pipeline, or [call the `migrate` function](#apply-schema-migrations-on-startup) when the deployed app starts. The migration resource from [Apply schema migrations on startup](#apply-schema-migrations-on-startup) configures a local run script; deploying it requires explicit runtime publishing configuration and a one-shot execution model for your deployment target. For publishing options, see [Deploy JavaScript apps](/deployment/javascript-apps/). + + +`RunDatabaseUpdateOnStart` affects only local runs. To apply migrations in a deployed environment, publish them as a container image with . 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 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: @@ -1128,6 +1428,79 @@ builder.Build().Run(); The Docker Compose methods come from the [📦 Aspire.Hosting.Docker](https://www.nuget.org/packages/Aspire.Hosting.Docker) package. Call `WithReference` on the migration resource so that the bundle container receives the database connection string, and `WaitFor` so that it starts only after the database is healthy. + + + + +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](#apply-schema-migrations-on-startup). To deploy the `api-migrate` resource from that section instead, call . The deployment then builds a container image that runs the `db:migrate` script. For other publishing options, see [Deploy JavaScript apps](/deployment/javascript-apps/). + +The `api-migrate` container exits after it applies the migrations. Configure each deployment target so that it doesn't restart the container: + +- On Azure Container Apps, publish the migration resource as a job with . A manually triggered job doesn't run until you start it. To start it during deployment, see [Ensure successful migrations deployment](#ensure-successful-migrations-deployment). +- On Docker Compose, set the service's restart policy to `no` with , as shown in the following example. +- On Kubernetes, customize the generated manifest to use a `Job` workload, or set `restartPolicy: OnFailure`. + + + + +```typescript title="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(); +``` + + + + +```csharp title="AppHost.cs" +var builder = DistributedApplication.CreateBuilder(args); + +builder.AddDockerComposeEnvironment("compose"); + +var postgres = builder.AddPostgres("postgres"); +var catalogdb = postgres.AddDatabase("catalogdb"); + +#pragma warning disable ASPIREJAVASCRIPT001 +var migrate = builder.AddJavaScriptApp("api-migrate", "../api", "db:migrate") + .WithReference(catalogdb) + .WaitFor(catalogdb) + .PublishAsPackageScript(scriptName: "db:migrate") + .PublishAsDockerComposeService((_, service) => service.Restart = "no"); +#pragma warning restore ASPIREJAVASCRIPT001 + +builder.AddNodeApp("api", "../api", "src/index.ts") + .WithReference(catalogdb) + .WaitForCompletion(migrate); + +builder.Build().Run(); +``` + + + + +The Docker Compose methods come from the [📦 Aspire.Hosting.Docker](https://www.nuget.org/packages/Aspire.Hosting.Docker) package. The container image includes only production dependencies, so list `drizzle-kit` under `dependencies` in _package.json_, not `devDependencies`. In a C# AppHost, the JavaScript publishing API is experimental and requires suppressing the [`ASPIREJAVASCRIPT001`](/diagnostics/aspirejavascript001/) diagnostic. + + + 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. @@ -1138,8 +1511,19 @@ Don't deploy development seed data or seed endpoints. Seed data that's part of y 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: + + - [Add a custom step to the Aspire deployment pipeline](#run-migrations-in-the-deployment-pipeline) so that `aspire deploy` runs a migration job and waits for it to succeed before it updates the app. -- [Run an EF Core migration bundle in your CI/CD pipeline](#run-a-migration-bundle-as-a-cicd-pre-deployment-step) before you call `aspire deploy`. +- [Run an EF Core migration bundle in your CI/CD pipeline](#run-migrations-as-a-cicd-pre-deployment-step) before you call `aspire deploy`. + + + + + +- [Add a custom step to the Aspire deployment pipeline](#run-migrations-in-the-deployment-pipeline) so that `aspire deploy` runs a migration job and waits for it to succeed before it updates the app. +- [Run `drizzle-kit migrate` in your CI/CD pipeline](#run-migrations-as-a-cicd-pre-deployment-step) before you call `aspire deploy`. + + 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. @@ -1155,7 +1539,9 @@ The following examples deploy to Azure Container Apps, so they need the [📦 As Aspire creates the Azure deployment steps while it resolves the pipeline, after your AppHost code adds its own steps. If you name an Azure step in the `dependsOn` or `requiredBy` options of a new step, the pipeline fails with an `unknown step` error. Instead, add the 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. -For EF Core, publish the migration bundle as a container image and deploy it as a manually triggered job with . 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`: + + +Publish the migration bundle as a container image and deploy it as a manually triggered job with . 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`: @@ -1352,9 +1738,11 @@ static async Task RunAzAsync(string[] args, CancellationToken cancellati -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`. In a C# AppHost, the pipeline API is experimental and requires suppressing the [`ASPIREPIPELINES001`](/diagnostics/aspirepipelines001/) diagnostic. + + + -For Drizzle, deploy the `db:migrate` script from [Apply schema migrations on startup](#apply-schema-migrations-on-startup) as a job. Call to build a container image that runs the script, and deploy the image as a manually triggered job. Then add the same custom step and configuration callback for the `api-migrate` job: +Deploy the `db:migrate` script from [Apply schema migrations on startup](#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`: @@ -1557,15 +1945,23 @@ static async Task RunAzAsync(string[] args, CancellationToken cancellati The container image includes only production dependencies, so list `drizzle-kit` under `dependencies` in _package.json_, not `devDependencies`. In a C# AppHost, the JavaScript publishing API is experimental and requires suppressing the [`ASPIREJAVASCRIPT001`](/diagnostics/aspirejavascript001/) diagnostic. + + +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`. In a C# AppHost, the pipeline API is experimental and requires suppressing the [`ASPIREPIPELINES001`](/diagnostics/aspirepipelines001/) diagnostic. + 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](/deployment/pipelines/), [Azure Container Apps jobs](/integrations/cloud/azure/container-app-jobs/), and [Jobs in Azure Container Apps](https://learn.microsoft.com/azure/container-apps/jobs) in the Azure documentation. -#### Run a migration bundle as a CI/CD pre-deployment step +#### 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. If it fails, the pipeline stops before `aspire deploy` runs. + + +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: @@ -1625,12 +2021,28 @@ 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. -Drizzle has no equivalent of a bundle, but you can follow the same order. Run `npx drizzle-kit migrate` in your CI/CD pipeline with the production connection string, and then run `aspire deploy`. - For more information, see [Migration bundles](https://learn.microsoft.com/ef/core/managing-schemas/migrations/applying#bundles) in the EF Core documentation and the [`aspire do` command](/reference/cli/commands/aspire-do/). + + + + +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](#apply-schema-migrations-on-startup) reads the connection string from the `CATALOGDB_URI` environment variable: + +```bash title="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. + + + ## See also - [PostgreSQL integration](/integrations/databases/postgres/postgres-host/) diff --git a/src/frontend/src/content/docs/integrations/databases/efcore/migrations.mdx b/src/frontend/src/content/docs/integrations/databases/efcore/migrations.mdx index f542831553..c73eda32d0 100644 --- a/src/frontend/src/content/docs/integrations/databases/efcore/migrations.mdx +++ b/src/frontend/src/content/docs/integrations/databases/efcore/migrations.mdx @@ -26,7 +26,7 @@ Since Aspire projects use a containerized architecture, databases are ephemeral In this article, you learn how to configure Aspire projects to run EF Core migrations during app startup. Before continuing, ensure your development environment is set up — see [Prerequisites](/get-started/prerequisites/). -For a comparison of the ways to create, seed, and migrate a database with EF Core or Drizzle, see [Aspire database patterns](/fundamentals/database-patterns/). +For a comparison of the ways to create, seed, and migrate a database with EF Core or Drizzle, see [Aspire database patterns](/fundamentals/database-patterns/?orm=efcore). ## Obtain the starter app @@ -211,7 +211,7 @@ Ensure you're running migration commands from the correct project: ## Create the migration service -To execute migrations, call the EF Core `Microsoft.EntityFrameworkCore.Migrations.IMigrator.Migrate` method or the `IMigrator.MigrateAsync` method. In this tutorial, you'll create a separate worker service to apply migrations. This approach separates migration concerns into a dedicated project, which is easier to maintain and allows migrations to run before other services start. For a condensed version of this pattern with a PostgreSQL database, and for the alternatives, see [Apply schema migrations on startup](/fundamentals/database-patterns/#apply-schema-migrations-on-startup). +To execute migrations, call the EF Core `Microsoft.EntityFrameworkCore.Migrations.IMigrator.Migrate` method or the `IMigrator.MigrateAsync` method. In this tutorial, you'll create a separate worker service to apply migrations. This approach separates migration concerns into a dedicated project, which is easier to maintain and allows migrations to run before other services start. For a condensed version of this pattern with a PostgreSQL database, and for the alternatives, see [Apply schema migrations on startup](/fundamentals/database-patterns/?orm=efcore#apply-schema-migrations-on-startup). :::note **Where to create migrations**: Migrations should be created in the project that contains your Entity Framework DbContext and model classes (in this example, *SupportTicketApi.Data*). The migration service project references this data project to apply the migrations at startup. @@ -551,7 +551,7 @@ The [Aspire Shop](https://learn.microsoft.com/samples/microsoft/aspire-samples/a In addition to creating a dedicated worker service as described above, Aspire provides a first-class AppHost API for managing EF Core migrations: . This API integrates migration execution directly into the AppHost orchestration and the Aspire publishing pipeline, without requiring a separate migration service project. -This section describes the API. For C# and TypeScript AppHost examples that apply migrations on startup, from a dashboard command, and during deployment, see [Aspire database patterns](/fundamentals/database-patterns/#modify-a-database-schema). +This section describes the API. For C# and TypeScript AppHost examples that apply migrations on startup, from a dashboard command, and during deployment, see [Aspire database patterns](/fundamentals/database-patterns/?orm=efcore#modify-a-database-schema). ### Add the package @@ -649,7 +649,7 @@ Key behaviors: #### Preventing container restarts per environment -A migration bundle is idempotent (running it twice is safe), but different compute environments need explicit configuration to avoid restarting the container after it exits. To make a deployment wait for the migrations to succeed before it updates the app, see [Ensure successful migrations deployment](/fundamentals/database-patterns/#ensure-successful-migrations-deployment). +A migration bundle is idempotent (running it twice is safe), but different compute environments need explicit configuration to avoid restarting the container after it exits. To make a deployment wait for the migrations to succeed before it updates the app, see [Ensure successful migrations deployment](/fundamentals/database-patterns/?orm=efcore#ensure-successful-migrations-deployment). @@ -687,7 +687,7 @@ Customize the generated manifest to use a `Job` workload or set `restartPolicy: ## See also -- [Aspire database patterns](/fundamentals/database-patterns/) +- [Aspire database patterns](/fundamentals/database-patterns/?orm=efcore) - [EF Core migrations](https://learn.microsoft.com/ef/core/managing-schemas/migrations/) - [Connection resiliency](https://learn.microsoft.com/ef/core/miscellaneous/connection-resiliency) - [Seed data in a database using Aspire](/integrations/databases/efcore/seed-database/) diff --git a/src/frontend/src/content/docs/integrations/databases/efcore/overview.mdx b/src/frontend/src/content/docs/integrations/databases/efcore/overview.mdx index 2f1bdfd02e..e19f9a677b 100644 --- a/src/frontend/src/content/docs/integrations/databases/efcore/overview.mdx +++ b/src/frontend/src/content/docs/integrations/databases/efcore/overview.mdx @@ -40,7 +40,7 @@ Aspire's EF Core integrations build on standard EF Core patterns and extend them - **Pooled `DbContext` by default** — `AddDbContext` registers a context pool automatically, reducing per-request allocation overhead. - **Built-in observability** — Health checks, OpenTelemetry distributed tracing, and connection-retry resiliency are enabled out of the box. - **Enrichment API** — When you need custom `AddDbContextPool` configuration, call `EnrichDbContext` afterwards to layer Aspire's defaults on top of your own setup. -- **Migrations support** — Run EF Core schema migrations at startup or publish them as container images for deployment. See [Apply EF Core migrations in Aspire](/integrations/databases/efcore/migrations/) and [Aspire database patterns](/fundamentals/database-patterns/). +- **Migrations support** — Run EF Core schema migrations at startup or publish them as container images for deployment. See [Apply EF Core migrations in Aspire](/integrations/databases/efcore/migrations/) and [Aspire database patterns](/fundamentals/database-patterns/?orm=efcore). - **.NET-only client code** — EF Core runs inside consuming .NET services; all `DbContext` registration code is C#. ## Supported EF Core integrations @@ -770,7 +770,7 @@ Only the base context state is reset when it's returned to the pool. If you've m - [Entity Framework Core documentation hub](https://learn.microsoft.com/ef/core) - [Apply Entity Framework Core migrations in Aspire](/integrations/databases/efcore/migrations/) - [Seed a database in Aspire](/integrations/databases/efcore/seed-database/) -- [Aspire database patterns](/fundamentals/database-patterns/) +- [Aspire database patterns](/fundamentals/database-patterns/?orm=efcore) - [Get started with the SQL Server EF Core integration](/integrations/databases/efcore/sql-server/sql-server-get-started/) - [Get started with the PostgreSQL EF Core integration](/integrations/databases/efcore/postgres/postgresql-get-started/) - [Get started with the MySQL EF Core integration](/integrations/databases/efcore/mysql/mysql-get-started/) diff --git a/src/frontend/src/content/docs/integrations/databases/efcore/seed-database.mdx b/src/frontend/src/content/docs/integrations/databases/efcore/seed-database.mdx index 2868e2e0bc..dc07de3a5d 100644 --- a/src/frontend/src/content/docs/integrations/databases/efcore/seed-database.mdx +++ b/src/frontend/src/content/docs/integrations/databases/efcore/seed-database.mdx @@ -19,7 +19,7 @@ import ApiReference from '@components/ApiReference.astro'; In this article, you learn how to configure Aspire projects to seed data in a database during app startup. Aspire enables you to seed data using database scripts or Entity Framework Core (EF Core) for common platforms such as SQL Server, PostgreSQL, and MySQL. -For PostgreSQL examples, and for other ways to seed a database such as custom dashboard commands, migrations, and Drizzle for JavaScript apps, see [Seed a database with sample data](/fundamentals/database-patterns/#seed-a-database-with-sample-data). +For PostgreSQL examples, and for other ways to seed a database such as custom dashboard commands, migrations, and Drizzle for JavaScript apps, see [Seed a database with sample data](/fundamentals/database-patterns/?orm=efcore#seed-a-database-with-sample-data). ## When to seed data @@ -167,7 +167,7 @@ The preceding code: PostgreSQL has no `USE` statement, so a script passed to `WithCreationScript()` runs against the default database. It can create other databases, but it can't add tables and data to them. Instead, copy your seed scripts into the container with , so that PostgreSQL runs them when it initializes the database. -For an example script and AppHost code, see [Seed a database in a dashboard REPL terminal](/fundamentals/database-patterns/#seed-a-database-in-a-dashboard-repl-terminal). +For an example script and AppHost code, see [Seed a database in a dashboard REPL terminal](/fundamentals/database-patterns/?orm=efcore#seed-a-database-in-a-dashboard-repl-terminal). @@ -301,7 +301,7 @@ if (app.Environment.IsDevelopment()) -For a PostgreSQL example, see [Seed a database on startup or using a custom command](/fundamentals/database-patterns/#seed-a-database-on-startup-or-using-a-custom-command). +For a PostgreSQL example, see [Seed a database on startup or using a custom command](/fundamentals/database-patterns/?orm=efcore#seed-a-database-on-startup-or-using-a-custom-command). @@ -376,7 +376,7 @@ The `UseSeeding` and `UseAsyncSeeding` methods provide several advantages over m ### Seed data manually -You can also seed data with your own code, outside the `UseSeeding` and `UseAsyncSeeding` options. For example, you can add rows from an endpoint that you call with a custom dashboard command, so that you seed only when you choose. For an example, see [Seed a database on startup or using a custom command](/fundamentals/database-patterns/#seed-a-database-on-startup-or-using-a-custom-command). +You can also seed data with your own code, outside the `UseSeeding` and `UseAsyncSeeding` options. For example, you can add rows from an endpoint that you call with a custom dashboard command, so that you seed only when you choose. For an example, see [Seed a database on startup or using a custom command](/fundamentals/database-patterns/?orm=efcore#seed-a-database-on-startup-or-using-a-custom-command). :::caution Run manual seed code only during development. Check the environment before you run it. @@ -384,7 +384,7 @@ Run manual seed code only during development. Check the environment before you r ## See also -- [Aspire database patterns](/fundamentals/database-patterns/) +- [Aspire database patterns](/fundamentals/database-patterns/?orm=efcore) - [Apply EF Core migrations in Aspire](/integrations/databases/efcore/migrations/) - [Aspire orchestration overview](/get-started/app-host/) - [EF Core seeding documentation](https://learn.microsoft.com/ef/core/modeling/data-seeding) From 613fafa55b33dbb4a6d0c312f2225755cbfde692 Mon Sep 17 00:00:00 2001 From: AJ Matthews Date: Mon, 23 Nov 2026 17:26:11 +0000 Subject: [PATCH 13/13] Fixed some problems after running the doc tester skill. --- .../docs/fundamentals/database-patterns.mdx | 65 ++++++++++++------- 1 file changed, 41 insertions(+), 24 deletions(-) diff --git a/src/frontend/src/content/docs/fundamentals/database-patterns.mdx b/src/frontend/src/content/docs/fundamentals/database-patterns.mdx index 3aa61fb02e..08f635999c 100644 --- a/src/frontend/src/content/docs/fundamentals/database-patterns.mdx +++ b/src/frontend/src/content/docs/fundamentals/database-patterns.mdx @@ -574,11 +574,11 @@ VALUES ON CONFLICT DO NOTHING; ``` -When Aspire later creates `catalogdb`, it finds the database 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. +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](#persist-a-database-across-restarts) 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 so that the resource doesn't run with the rest of the app. The resource receives the database's connection information from `WithReference`, in the same way as the app. +To run a separate seed program, add it to the AppHost as a resource that you start from the dashboard. Call 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. @@ -757,7 +757,7 @@ builder.Services.AddHostedService(); builder.Build().Run(); ``` -The worker applies the migrations inside an execution strategy, so EF Core retries them after a transient connection error. It then stops the app: +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: ```csharp title="MigrationService/Worker.cs" using Microsoft.EntityFrameworkCore; @@ -768,13 +768,25 @@ public class Worker( { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { - using var scope = serviceProvider.CreateScope(); - var context = scope.ServiceProvider.GetRequiredService(); - - var strategy = context.Database.CreateExecutionStrategy(); - await strategy.ExecuteAsync(() => context.Database.MigrateAsync(stoppingToken)); + try + { + using var scope = serviceProvider.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); - lifetime.StopApplication(); + 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(); + } } } ``` @@ -826,7 +838,7 @@ builder.Build().Run(); -If the migrations fail, the worker exits with an error and the app doesn't start. For a step-by-step tutorial that builds a migration service, see [Apply EF Core migrations in Aspire](/integrations/databases/efcore/migrations/#create-the-migration-service). +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](/integrations/databases/efcore/migrations/#create-the-migration-service). @@ -959,7 +971,7 @@ await api.withReference(catalogdb); // No RunDatabaseUpdateOnStart call, so migrations run only from the dashboard. const migrations = await api.addEFMigrations('api-migrations'); -await migrations.withMigrationsProject('../Data/Data.csproj'); +await migrations.withMigrationsProject({ migrationsProject: '../Data/Data.csproj' }); await builder.build().run(); ``` @@ -1426,7 +1438,7 @@ builder.Build().Run(); -The Docker Compose methods come from the [📦 Aspire.Hosting.Docker](https://www.nuget.org/packages/Aspire.Hosting.Docker) package. Call `WithReference` on the migration resource so that the bundle container receives the database connection string, and `WaitFor` so that it starts only after the database is healthy. +The Docker Compose methods come from the [📦 Aspire.Hosting.Docker](https://www.nuget.org/packages/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. @@ -1434,6 +1446,19 @@ The Docker Compose methods come from the [📦 Aspire.Hosting.Docker](https://ww 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](#apply-schema-migrations-on-startup). To deploy the `api-migrate` resource from that section instead, call . The deployment then builds a container image that runs the `db:migrate` script. For other publishing options, see [Deploy JavaScript apps](/deployment/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: + +```json title="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](/integrations/frameworks/javascript/#customize-scripts). + The `api-migrate` container exits after it applies the migrations. Configure each deployment target so that it doesn't restart the container: - On Azure Container Apps, publish the migration resource as a job with . A manually triggered job doesn't run until you start it. To start it during deployment, see [Ensure successful migrations deployment](#ensure-successful-migrations-deployment). @@ -1479,13 +1504,11 @@ builder.AddDockerComposeEnvironment("compose"); var postgres = builder.AddPostgres("postgres"); var catalogdb = postgres.AddDatabase("catalogdb"); -#pragma warning disable ASPIREJAVASCRIPT001 var migrate = builder.AddJavaScriptApp("api-migrate", "../api", "db:migrate") .WithReference(catalogdb) .WaitFor(catalogdb) .PublishAsPackageScript(scriptName: "db:migrate") .PublishAsDockerComposeService((_, service) => service.Restart = "no"); -#pragma warning restore ASPIREJAVASCRIPT001 builder.AddNodeApp("api", "../api", "src/index.ts") .WithReference(catalogdb) @@ -1497,7 +1520,7 @@ builder.Build().Run(); -The Docker Compose methods come from the [📦 Aspire.Hosting.Docker](https://www.nuget.org/packages/Aspire.Hosting.Docker) package. The container image includes only production dependencies, so list `drizzle-kit` under `dependencies` in _package.json_, not `devDependencies`. In a C# AppHost, the JavaScript publishing API is experimental and requires suppressing the [`ASPIREJAVASCRIPT001`](/diagnostics/aspirejavascript001/) diagnostic. +The Docker Compose methods come from the [📦 Aspire.Hosting.Docker](https://www.nuget.org/packages/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. @@ -1537,7 +1560,7 @@ The `aspire deploy` command runs a pipeline of named steps, such as `provision-a The following examples deploy to Azure Container Apps, so they need the [📦 Aspire.Hosting.Azure.AppContainers](https://www.nuget.org/packages/Aspire.Hosting.Azure.AppContainers) package. Aspire creates or updates each container app or job in a step named `provision--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. If you name an Azure step in the `dependsOn` or `requiredBy` options of a new step, the pipeline fails with an `unknown step` error. Instead, add the 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. +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. @@ -1655,7 +1678,6 @@ api.AddEFMigrations("api-migrations") if (builder.ExecutionContext.IsPublishMode) { -#pragma warning disable ASPIREPIPELINES001 builder.Pipeline.AddStep("run-api-migrations", async context => { var config = context.Services.GetRequiredService(); @@ -1709,7 +1731,6 @@ if (builder.ExecutionContext.IsPublishMode) return Task.CompletedTask; }); -#pragma warning restore ASPIREPIPELINES001 } builder.Build().Run(); @@ -1846,13 +1867,11 @@ var postgres = builder.AddPostgres("postgres"); var catalogdb = postgres.AddDatabase("catalogdb"); // Deploy the db:migrate script as a manually triggered job. -#pragma warning disable ASPIREJAVASCRIPT001 var migrate = builder.AddJavaScriptApp("api-migrate", "../api", "db:migrate") .WithReference(catalogdb) .WaitFor(catalogdb) .PublishAsPackageScript(scriptName: "db:migrate") .PublishAsAzureContainerAppJob(); -#pragma warning restore ASPIREJAVASCRIPT001 builder.AddNodeApp("api", "../api", "src/index.ts") .WithReference(catalogdb) @@ -1860,7 +1879,6 @@ builder.AddNodeApp("api", "../api", "src/index.ts") if (builder.ExecutionContext.IsPublishMode) { -#pragma warning disable ASPIREPIPELINES001 builder.Pipeline.AddStep("run-api-migrations", async context => { var config = context.Services.GetRequiredService(); @@ -1914,7 +1932,6 @@ if (builder.ExecutionContext.IsPublishMode) return Task.CompletedTask; }); -#pragma warning restore ASPIREPIPELINES001 } builder.Build().Run(); @@ -1943,11 +1960,11 @@ static async Task RunAzAsync(string[] args, CancellationToken cancellati -The container image includes only production dependencies, so list `drizzle-kit` under `dependencies` in _package.json_, not `devDependencies`. In a C# AppHost, the JavaScript publishing API is experimental and requires suppressing the [`ASPIREJAVASCRIPT001`](/diagnostics/aspirejavascript001/) diagnostic. +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`. In a C# AppHost, the pipeline API is experimental and requires suppressing the [`ASPIREPIPELINES001`](/diagnostics/aspirepipelines001/) diagnostic. +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.