EF Core Migrations
Your database schema as code. Rollback in 10s. 4 mins.
Your First "Aha" Moment: Migrations = Git for your database. Undo a schema change like Ctrl+Z.
1. The Problem: "It Works on My Machine"
Without Migrations: You add Email to User class. Deploy. Prod crashes: Invalid column 'Email'. You forgot to run SQL on prod DB. Manager angry.
With Migrations: You run Add-Migration AddUserEmail. EF generates C# code + SQL. Commit to git. CI/CD runs Update-Database on deploy. Zero missed steps.
2. The 3 Commands You Need
| Command | What It Does |
|---|---|
Add-Migration Init | Compares models vs last snapshot. Generates C# file with Up() and Down(). |
Update-Database | Runs Up() methods to apply to DB. Creates __EFMigrationsHistory table. |
Remove-Migration | Deletes last migration if NOT applied yet. Ctrl+Z before you deploy. |
3. See It Work - 60 Seconds
Step 1: Add property public string Phone { get; set; } to User class.
Step 2: PMC โ Add-Migration AddUserPhone
public partial class AddUserPhone : Migration {
protected override void Up(MigrationBuilder mb) {
mb.AddColumn(name: "Phone", table: "Users", nullable: true);
}
protected override void Down(MigrationBuilder mb) {
mb.DropColumn(name: "Phone", table: "Users");
}
}
Step 3: Update-Database. Column added. No SQL written by you.
Career-Killer Mistake #1: Editing a migration file AFTER
What happens: Your DB has Migration_A. Your code has Migration_A_Edited. Hash mismatch.
Fix: Never edit applied migration. Add a new migration to fix it.
Update-Database. What happens: Your DB has Migration_A. Your code has Migration_A_Edited. Hash mismatch.
Update-Database fails forever. Team blocked. Fix: Never edit applied migration. Add a new migration to fix it.
Stop Here. Think. Migrations are code. They go in git. They get code reviewed. DBAs love this.
Next:
Next:
Script-Migration. How to give SQL to your DBA so they stop yelling at you.
Quick Check ๐ง
Ready for LINQ? You can change schemas safely. Next: LINQ Queries teaches
Include vs N+1, AsNoTracking for perf, and why First() throws in prod. Let's go โ
No comments yet. Be the first to share your thoughts!