Entity Framework Core Migrations ๐
The Story of Your Databaseโs Time Machine
Imagine you have a LEGO castle. Every day, you want to add new towers, move walls, or change windows. But hereโs the problemโyou canโt just tear it all down and rebuild from scratch every time!
EF Core Migrations are like a magical time machine for your database. They keep a journal of every change you make, so you can:
- Add new rooms (tables) without losing your furniture (data)
- Rearrange things safely
- Go back in time if something goes wrong!
๐๏ธ Two Ways to Build: Code First vs Database First
Think of building a house. You can either:
- Draw the blueprints FIRST, then build (Code First)
- Look at an existing house and create blueprints from it (Database First)
๐จ Code First Approach
What is it? You write C# classes (your blueprints), and EF Core creates the database tables for you!
Simple Example: Imagine you want to store information about your pets.
// Your C# class (the blueprint)
public class Pet
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
What happens:
- You write this class
- EF Core reads it
- EF Core creates a โPetsโ table with columns: Id, Name, Age
Real Life Analogy: You tell a builder: โI want a room with a bed, a window, and a door.โ The builder creates exactly that room for you!
graph TD A["๐ Write C# Classes"] --> B["๐ง Create Migration"] B --> C["๐ฆ Apply Migration"] C --> D["๐๏ธ Database Created!"]
When to use Code First:
- โ Starting a brand new project
- โ You prefer writing code over using database tools
- โ You want version control for your database changes
๐ Database First Approach
What is it? You already have a database, and EF Core creates C# classes that match it!
Simple Example: Your database already has a โStudentsโ table with columns: StudentId, FirstName, LastName.
EF Core will create:
// EF Core generates this for you!
public class Student
{
public int StudentId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Real Life Analogy: You have an existing LEGO castle. You take photos and draw blueprints of whatโs already there, so you can understand it and modify it!
graph TD A["๐๏ธ Existing Database"] --> B["๐ง Scaffold Command"] B --> C["๐ C# Classes Created"] C --> D["โจ Ready to Use!"]
When to use Database First:
- โ Working with an existing database
- โ Database was designed by someone else
- โ You need to quickly connect to a legacy system
๐ Creating Migrations
What is a Migration? A migration is like a diary entry that says: โToday, I made these changes to the database.โ
Think of it like this:
- Monday: Added a โPetsโ table โก๏ธ Migration #1
- Wednesday: Added โColorโ column to Pets โก๏ธ Migration #2
- Friday: Removed โAgeโ column from Pets โก๏ธ Migration #3
Each migration remembers EXACTLY what changed!
The Magic Command:
dotnet ef migrations add YourMigrationName
Real Example:
dotnet ef migrations add AddPetsTable
What happens behind the scenes:
graph TD A["๐ EF Looks at Your Classes"] --> B["๐ Compares to Database"] B --> C["๐ Creates Migration File"] C --> D["โ Changes Recorded!"]
What you get: A new file with two important methods:
Up()- How to make the changeDown()- How to undo the change
public partial class AddPetsTable : Migration
{
protected override void Up(
MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Pets",
columns: table => new
{
Id = table.Column<int>(),
Name = table.Column<string>()
});
}
protected override void Down(
MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Pets");
}
}
Naming Tips:
- โ
AddPetsTable(clear!) - โ
AddEmailToUsers(specific!) - โ
Update1(confusing!) - โ
Changes(what changes?!)
๐ Applying Migrations
What does โapplyingโ mean? It means actually MAKING the changes to your database!
Creating a migration = Writing a recipe Applying a migration = Cooking the food!
The Magic Command:
dotnet ef database update
What happens:
graph TD A["๐ Read All Migrations"] --> B[๐ Check What's Applied] B --> C["โก Run New Migrations"] C --> D["๐ Database Updated!"]
EF Core is SMART!
It keeps track of which migrations are already applied in a special table called __EFMigrationsHistory. So if you run the command twice, it wonโt repeat anything!
Going Back in Time: Made a mistake? You can roll back!
dotnet ef database update PreviousMigrationName
Example:
# Applied these migrations:
# 1. InitialCreate
# 2. AddPetsTable
# 3. AddColorToPets (oops, mistake!)
# Go back to AddPetsTable
dotnet ef database update AddPetsTable
๐ ๏ธ Migrations CLI (Command Line Interface)
The CLI is your remote control for migrations. Here are all the buttons:
Essential Commands
| Command | What It Does |
|---|---|
dotnet ef migrations add Name |
Create a new migration |
dotnet ef migrations list |
See all migrations |
dotnet ef migrations remove |
Delete the last migration |
dotnet ef database update |
Apply all pending migrations |
dotnet ef database drop |
Delete the entire database |
Common Scenarios
๐ Starting Fresh:
dotnet ef migrations add InitialCreate
dotnet ef database update
โ Adding a New Feature:
# Changed your C# classes? Create a migration!
dotnet ef migrations add AddNewFeature
dotnet ef database update
๐ Oops, Made a Mistake:
# If migration NOT applied yet:
dotnet ef migrations remove
# If migration IS applied:
dotnet ef database update PreviousMigration
dotnet ef migrations remove
๐ Generate SQL Script:
dotnet ef migrations script
This gives you the SQL commands without running themโgreat for production!
๐ฏ Targeting a Specific Migration:
# Apply up to a specific migration
dotnet ef database update TargetMigration
# Generate script from one to another
dotnet ef migrations script From To
๐ฎ Quick Reference Card
graph TD subgraph "Your Workflow" A["1๏ธโฃ Change C# Classes"] --> B["2๏ธโฃ Add Migration"] B --> C["3๏ธโฃ Review Migration"] C --> D["4๏ธโฃ Update Database"] end
The Complete Flow
- Make changes to your C# model classes
- Create migration with
dotnet ef migrations add - Review the generated migration file
- Apply changes with
dotnet ef database update - Commit everything to source control!
๐ก Pro Tips
๐ Always Name Migrations Clearly Future you will thank present you!
๐ Review Before Applying Check the generated migration fileโmake sure it does what you expect.
๐ One Change = One Migration Donโt bundle unrelated changes. Keep migrations focused.
๐ Never Edit Applied Migrations Once a migration is in the database, create a new one instead.
๐ Use Scripts for Production Generate SQL scripts instead of running migrations directly on production databases.
๐ You Did It!
You now understand:
- โ Code First - Write classes, database follows
- โ Database First - Database exists, classes follow
- โ Creating Migrations - Capture your changes
- โ Applying Migrations - Make changes real
- โ CLI Commands - Your migration remote control
Migrations are your databaseโs best friend. They keep everything safe, organized, and reversible. No more fear of making changes!
Remember: Every great app started with its first migration. Now go build something amazing! ๐
