Database Upgrade Events
Summary
The database upgrade system uses an event-driven approach to handle schema migrations. When the application starts, it compares the current EF Core model against the live database schema. When differences are detected — such as new columns, removed columns, new tables, or removed tables — subscriber methods are invoked to run data migration scripts before the schema change completes.
This system also supports feature version upgrades, which are versioned data transformations that run independently of schema changes and are tracked in a __FeatureVersion table.
How It Works
On startup, the DatabaseUpgrader orchestrates the upgrade:
Lock database → Create temp schema from EF model → Compare schemas
→ Invoke migration subscribers → Apply schema changes → Feature version upgrades → Unlock
- The database is locked to prevent concurrent upgrades
- A temporary schema is generated from the current EF Core model
- The temp schema is compared against the public schema to detect changes
- For each detected change, matching subscriber methods are invoked
- Subscribers emit SQL scripts via
args.UpgradeScript(sql)to migrate data - All scripts run in a single transaction
- Feature version upgrades run after schema migration
Event Reference
Schema Migration Events
| Event | Description |
|---|---|
| PropertyAdded | Fires when a new column is added to an existing table. Use to populate the new column with initial data. |
| PropertyDeleted | Fires when a column is removed from a table. Use to migrate data to other columns before removal. |
| EntityAdded | Fires when a new table is created. Use to seed initial data or migrate data from other tables. |
| EntityDeleted | Fires when a table is removed. Use to migrate data to replacement tables before removal. |
Feature Version Events
| Event | Description |
|---|---|
| FeatureVersionChanged | Fires for versioned data upgrades that are independent of schema changes. Version state is tracked in the database. |
Base Event Args
All migration event args inherit from MigrationEventArgs, which provides:
| Method | Description |
|---|---|
UpgradeScript(string sql) |
Adds a SQL script to be executed after all subscribers have been invoked |
ReadFromDatabase(string sql) |
Reads data from the current database to help generate migration scripts (read-only) |
Notes
- Subscribers are discovered automatically via reflection across all loaded assemblies.
- All migration scripts run within a single transaction — if any script fails, the entire upgrade is rolled back.
- NOT NULL constraint changes are applied last, after all subscriber scripts have run.
- Schema migration subscribers fire based on detected schema differences — they do not fire if the schema has not changed.
- Feature version upgrades are tracked in the
__FeatureVersiontable and only run once per version.