/DB

Generate and apply migrations

Configure the database, generate PostgreSQL DDL from the annotated models with the bundled CLI, and apply it at startup with one generated call.

updated 5 Jun 20262 min readv0.3.2View as Markdown

The generator turns your classes into typed C#. A second tool, the bundled migration CLI, turns the same classes into PostgreSQL DDL. Both read the identical [Table] metadata, so the schema and the code never drift.

Configure the database

Add socigy.json to the model assembly. It names the database and selects the platform, which is what tells the generator to emit the context, factory, and DI extensions.

// TaskApi.AppDb/socigy.json
{
  "database": {
    "platform": "postgresql",
    "databaseName": "AppDb"
  }
}

databaseName becomes the prefix for every generated type: IAppDb, AddAppDb(), EnsureLatestAppDbMigration(). See Configuration for every field.

Generate the migration

The migration CLI runs automatically as part of the build. There is no separate command to invoke: building the model project in the DB_Migration configuration triggers it through an MSBuild target the package registers.

dotnet build TaskApi.AppDb/TaskApi.AppDb.csproj -c DB_Migration

Each run writes a timestamped .g.cs migration class into Socigy/Migrations/ and records a Socigy/structure.json snapshot of the model. The DDL lives inside the migration class as up and down SQL. The first run emits a full CREATE TABLE baseline for projects and tasks (primary keys, the unique constraint, and the foreign key); later builds diff against structure.json and emit only the ALTER TABLE statements needed to catch up. Because each migration is plain C#, it compiles into the assembly where the runtime migration manager can apply it. See Schema generation and the CLI tool for details.

Apply on startup

Point a connection string at your database in the host project. The factory appends Database=AppDb for you, so omit the database name:

// TaskApi.Web/appsettings.json
{
  "ConnectionStrings": {
    "AppDb": { "Default": "Host=localhost;Username=app;Password=secret" }
  }
}

After builder.Build(), the generated EnsureLatestAppDbMigration() extension creates the database if needed and applies every pending migration before the app serves traffic:

var app = builder.Build();
await app.EnsureLatestAppDbMigration();
app.Run();
TIP
In tests or worker processes where there is no WebApplication, resolve the keyed IMigrationManager and call EnsureLatestVersion() directly. See Applying migrations.

The database now matches the model. Next, wire the typed context into the app: Wire up the context.