Sub topic 6
Creating the Database with Migrations
You now have entity classes and a BloggingContext. The database file does not exist yet. Migrations are how EF Core builds it.
What a Migration Is
A migration is a small C# file that describes one change to your database schema. The schema is the shape of the database: its tables, columns, and keys.
EF Core compares your current model (your classes and context) with the last migration it made. Then it writes code for the difference. You never write the CREATE TABLE statements yourself.
Migrations matter because databases change over time. Each migration is one step in that history, so every copy of the database can be brought up to date the same way.
Creating and Applying the First Migration
Run these two commands in your project folder:
dotnet ef migrations add InitialCreate
dotnet ef database updateThe first command creates a Migrations folder with three files:
| File | What it holds |
|---|---|
| `..._InitialCreate.cs` | `Up` and `Down` methods. `Up` creates the tables. `Down` undoes them. |
| `..._InitialCreate.Designer.cs` | Details EF Core needs about this migration. |
| `BloggingContextModelSnapshot.cs` | A picture of your whole model right now. |
The second command runs the migration. It creates blogging.db with a Blogs table and a Posts table. It also adds a table named __EFMigrationsHistory, where EF Core records which migrations it has already applied.
Changing the Model Later
Say you want each blog to have a rating. Add a property to Blog:
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 make and apply a new migration:
dotnet ef migrations add AddBlogRating
dotnet ef database updateEF Core sees only the new column. Its Up method adds Rating to Blogs and leaves your existing data alone.
Fixing a Mistake
If you made a migration but have not applied it yet, you can delete it:
dotnet ef migrations removeThis removes the newest migration and updates the snapshot.
Common Errors
- "dotnet-ef not found": install the tool with
dotnet tool install --global dotnet-ef. - "Your startup project doesn't reference Microsoft.EntityFrameworkCore.Design": add that package to the project.
- Build errors: the project must compile before EF Core can read your model. Fix the build first.
Exercise
You added a Rating property and ran dotnet ef migrations add AddBlogRating, but the Blogs table still has no Rating column. What step did you miss?
Show answer
You did not apply the migration. Run dotnet ef database update to execute its Up method against the database.
Exercise
What is the __EFMigrationsHistory table for?
Show answer
It records which migrations have already been applied, so database update runs only the ones that are new.