#csharp #dotnet #backend

Day 17: EF Core Migrations

Welcome to Day 17. Yesterday, we set up AppDbContext and our Book class. We told the app how to connect to a database, but the actual database doesn’t exist yet!

We use Migrations to generate the database schema automatically from our C# classes. This is called the Code-First approach.

Step 1: Install the EF Tools

You need the dotnet ef command-line tool installed on your machine globally to handle migrations.

dotnet tool install --global dotnet-ef

Step 2: Create a Migration

A migration is a snapshot of your C# models at a specific point in time.

Run this command in the same folder as your .csproj file:

dotnet ef migrations add InitialCreate

EF Core reads your AppDbContext, looks at the DbSet<Book>, and generates a new folder called Migrations. Inside, it creates a C# file with instructions on how to create the table using SQL (CREATE TABLE "Books" (...)).

Step 3: Apply the Migration

The migration files exist in your C# code, but we still haven’t touched the actual database file. To run the migration and generate the physical library.db file, run:

dotnet ef database update

Boom! You now have a working SQLite database with a Books table!

Modifying the Database

What happens if requirements change and we need to add an ISBN string to the Book class?

  1. Add the property to your C# class: public string ISBN { get; set; }
  2. Create a new migration: dotnet ef migrations add AddedISBN
  3. Update the database: dotnet ef database update

EF Core will intelligently generate ALTER TABLE SQL statements to modify your existing table without deleting your data!

Automatic Database Creation on Startup (Optional)

In production, you usually want to run dotnet ef database update manually during a CI/CD pipeline. But for local development, you can tell the server to just apply any pending migrations immediately when it boots up.

In Program.cs, after builder.Build(), add this:

var app = builder.Build();

// Create a temporary scope to get the DbContext and migrate it
using (var scope = app.Services.CreateScope())
{
    var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
    db.Database.Migrate();
}

Challenge for Day 17

Add a Genre string property to your Movie class from yesterday. Generate a migration called AddGenre and update your database!

Tomorrow: CRUD Operations with EF Core!