# 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.

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.

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

`databaseName` becomes the prefix for every generated type: `IAppDb`, `AddAppDb()`, `EnsureLatestAppDbMigration()`. See [Configuration](/database/0.3.2/getting-started/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.

```bash
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](/database/0.3.2/migration/schema-generation) and the [CLI tool](/database/0.3.2/migration/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:

```json
// 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:

```csharp
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](/database/0.3.2/migration/applying).

The database now matches the model. Next, wire the typed context into the app: [Wire up the context](/database/0.3.2/tutorial/context).
