Data layer and SQL
Migrations: managing the schema as code
Versioning, reviewing and safely shipping the database schema.
Understand the concept
EF Core migrations generate database schema changes from changes in model classes. Each migration is a C# file: Up defines moving to the new schema, Down the way back. Migrations live in the repository with the source code, so the schema is versioned, reviewed and applied to every environment in the same order, just like code.
Always read a generated migration. Renaming a column can be interpreted by EF Core as ‘drop the column, add a new one’ and lose data. Adding a column or creating an index on a large table can hold locks. Before applying migrations in production the database is backed up and the SQL script (dotnet ef migrations script) is reviewed.
Safe change in a live system is usually staged: first add the new column as nullable, ship the app writing both columns, migrate the data, finally drop the old column. This ‘expand and contract’ approach avoids downtime in deployments where old and new app versions briefly run side by side.
Schema changes are the hardest changes to undo; an unplanned migration loses data.
Applying a generated migration to production without reading it.
One topic. Three levels of depth.
dotnet ef migrations add AddPostReadingTime \
--project AtaberkSahin2.Infrastructure --startup-project AtaberkSahin2.Api
dotnet ef database update --project AtaberkSahin2.Infrastructure --startup-project AtaberkSahin2.ApiCreating and applying a migration; in this project the DbContext lives in Infrastructure and the startup project is Api.
This page connects to no real server or database. Code samples are illustrative for .NET 8, Next.js and SQL Server; timings are example values in the simulation, not measurements. Try samples only in your own development environment; never share real connection strings, tokens or passwords.
Try it yourself first.
You want to split the FullName column in Users into FirstName and LastName. List the steps for a zero-downtime release.
Show the solution and explanation
1) FirstName ve LastName’i nullable ekle (migration).
2) Uygulamayı her üç kolonu da yazacak şekilde yayınla.
3) Mevcut veriyi FullName’den böl ve doldur (veri betiği).
4) Uygulamayı yalnız yeni kolonları okuyup yazacak şekilde yayınla.
5) FullName’i kaldır (son migration).Expand and contract: at every step both the old and new app versions keep working.