Sub topic 6
Creating the Database with Migrations
In the last chapters you wrote C# classes (Blog and Post) and a BloggingContext that points at a SQLite file. The database itself does not exist yet. This chapter shows how EF Core builds it for you, and how it updates the database later when your classes change.
What a migration is
A schema is the shape of a database: which tables it has, which columns each table has, and how tables link together. A migration is a small C# file that describes one change to the schema, such as "create the Blogs table" or "add a Rating column."
EF Core writes migrations for you. It compares your current classes (the model) with a saved copy of the model from the last migration. Then it writes code for the difference.
Migrations matter for three reasons:
- You never write
CREATE TABLEby hand. - Each change is saved as a file, so it can go into source control with your code.
- Every copy of the database, on your laptop or on a server, can be brought to the same shape by running the same steps.
Creating your first migration
Open a terminal in the project folder, the one that holds EfCoreDemo.csproj. You installed the dotnet-ef tool and the Microsoft.EntityFrameworkCore.Design package during setup. Both are needed here.
dotnet ef migrations add InitialCreate
dotnet ef database updateThe first command builds your project, reads the model, and creates a Migrations folder. InitialCreate is just a name. Pick names that say what changed, the way you would write a commit message.
The second command runs the migration against the database. SQLite creates blogging.db if it is missing, then creates the Blogs and Posts tables.
What is inside the Migrations folder
The folder now holds three files:
| File | Purpose |
|---|---|
| `20261123101500_InitialCreate.cs` | The migration itself, with `Up` and `Down` methods |
| `20261123101500_InitialCreate.Designer.cs` | Metadata EF Core uses to identify the migration |
| `BloggingContextModelSnapshot.cs` | A full picture of the model as of the latest migration |
The number at the front is a timestamp. It keeps migrations in the order you made them.
Here is the main migration file, shortened to show only the Blogs table:
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace EfCoreDemo.Migrations
{
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Blogs",
columns: table => new
{
BlogId = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Url = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Blogs", x => x.BlogId);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(name: "Blogs");
}
}
}Up applies the change. Down undoes it. EF Core runs Down when you roll a database back to an earlier migration.
The snapshot file is how EF Core knows what changed next time. Do not edit it by hand.
How EF Core remembers what ran
When you ran database update, EF Core also created a table called __EFMigrationsHistory. It holds one row per applied migration, with the migration's full name and the EF Core version.
Each time you run database update, EF Core reads this table and applies only the migrations that are missing. Running the command twice in a row is safe. The second run finds nothing to do.
Changing the model later
Real projects change. Say you want to store a star rating for each blog. Add a property to the Blog class:
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; } = "";
public int Rating { get; set; }
public List<Post> Posts { get; } = new();
}Then create and apply a second migration:
dotnet ef migrations add AddBlogRating
dotnet ef database updateThe new migration's Up method contains only the difference:
migrationBuilder.AddColumn<int>(
name: "Rating",
table: "Blogs",
type: "INTEGER",
nullable: false,
defaultValue: 0);Existing rows keep their data. Each existing blog gets a Rating of 0, because the column cannot be empty and 0 is the default for int.
Useful migration commands
| Command | What it does |
|---|---|
| `dotnet ef migrations add Name` | Creates a new migration from model changes |
| `dotnet ef database update` | Applies all pending migrations |
| `dotnet ef database update InitialCreate` | Moves the database to that migration, running `Down` for later ones |
| `dotnet ef database update 0` | Undoes every migration |
| `dotnet ef migrations list` | Lists migrations and shows which are pending |
| `dotnet ef migrations remove` | Deletes the last migration file, if it has not been applied |
| `dotnet ef migrations script` | Prints the SQL for all migrations without running it |
Fixing a mistake
Suppose you added a migration and then noticed a typo in a property name. If you have not run database update yet, run dotnet ef migrations remove. Fix the class, then add the migration again.
If you already applied it, first roll the database back, then remove it:
dotnet ef database update InitialCreate
dotnet ef migrations removeIf the migration is already applied on a shared or production database, do not remove it. Add a new migration that fixes the problem instead.
Getting SQL for a server
On a production server you often cannot run dotnet ef. Generate a SQL file and give it to whoever runs the database:
dotnet ef migrations script --idempotent -o migrate.sqlAn idempotent script checks the history table before each step. That makes it safe to run on a database at any earlier migration.
Applying migrations from code
You can also apply migrations when the app starts:
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
await db.Database.MigrateAsync();
Console.WriteLine("Database is up to date.");This works well for small apps and demos. For apps that run on several servers at once, a SQL script or a separate deployment step is safer, so two copies of the app do not try to change the schema at the same moment.
Exercise
You add a string Description property to Post and run dotnet ef migrations add AddPostDescription, but you have not run database update yet. You realize you meant to name it Summary. What steps fix this cleanly?
Show answer
Run dotnet ef migrations remove to delete the unapplied migration. Rename the property to Summary, then run dotnet ef migrations add AddPostSummary and dotnet ef database update.
Exercise
You run dotnet ef database update twice in a row. What happens the second time, and why?
Show answer
Nothing changes. EF Core reads the __EFMigrationsHistory table, sees every migration is already recorded, and has no pending migrations to apply.
Exercise
Why should you read a migration before applying it when you have renamed a property?
Show answer
EF Core may treat the rename as dropping the old column and adding a new one, which deletes the column's existing data. Reading the file lets you change it to a RenameColumn call.