Code First and Migrations — The Schema Follows Your Classes
ReadingRoom's Book class needs an ISBN. You could log into the database and add a column by hand — then do it again on the test server, and again in production, and hope nobody forgets. Code first reverses the direction: you change the C# class, and EF Core generates a versioned script that changes every database the same way.
The rule
Change the class, add a migration, update the database.
Migrations need the EF tools once per machine and the design package once per project:
dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.DesignThen the loop is always the same:
dotnet ef migrations add AddBookIsbn # compare model to snapshot, write a migration
dotnet ef database update # apply pending migrations to the databaseA migration is a C# class with two methods:
public partial class AddBookIsbn : Migration
{
protected override void Up(MigrationBuilder mb) =>
mb.AddColumn<string>(name: "Isbn", table: "Books", nullable: true);
protected override void Down(MigrationBuilder mb) =>
mb.DropColumn(name: "Isbn", table: "Books");
}Up moves the schema forward; Down undoes it. EF records every applied migration in a table called __EFMigrationsHistory, so each database knows exactly which steps it has had. A model snapshot file in the project remembers the last known model, which is how the next migrations add works out what changed.
Useful extras: dotnet ef migrations remove deletes the last migration if it has not been applied; dotnet ef migrations script produces plain SQL you can review and run in a deployment.
Rules like maximum lengths and relationships come from attributes ([MaxLength(20)]) or from OnModelCreating in the DbContext, and they flow into migrations too.
The shortcut
Treat migrations like commits for your schema: one small, named migration per model change, committed to Git with the code that needs it.
Change the model
Add
public string? Isbn { get; set; }toBook.
The trap: renaming a property and trusting the migration blindly. EF may generate "drop column, add column", which deletes the data. Read every migration before applying it.
Drills
Answer fast — trust the rule.
You changed an entity class. What comes next?
What does a migration's Down method do?
How does a database know which migrations it already has?
Why read a generated migration before applying it?
Remember
- Change the class, add a migration, update the database.
- One small, named migration per change, committed with the code.
- Read every migration; renames can become drop-and-add.
