Migrations

Back

Loading concept...

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:

  1. Draw the blueprints FIRST, then build (Code First)
  2. 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 change
  • Down() - 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&#35; Classes"] --> B["2๏ธโƒฃ Add Migration"] B --> C["3๏ธโƒฃ Review Migration"] C --> D["4๏ธโƒฃ Update Database"] end

The Complete Flow

  1. Make changes to your C# model classes
  2. Create migration with dotnet ef migrations add
  3. Review the generated migration file
  4. Apply changes with dotnet ef database update
  5. 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! ๐Ÿš€

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.