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.