Roadmap › Entity Framework (EF6 & EF Core) › Module: Getting Started
Lessons in this course (15)

3. Code-first vs database-first and migrations

Basic★ Must knowLesson 3 of 15
bash
dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design

dotnet ef migrations add InitialCreate          # creates Migrations/xxxx_InitialCreate.cs + model snapshot
dotnet ef database update                       # applies pending migrations (__EFMigrationsHistory table)
dotnet ef migrations remove                     # removes the last, unapplied migration
dotnet ef migrations script --idempotent -o deploy.sql   # SQL for DBAs / pipelines
dotnet ef migrations bundle --self-contained    # executable that applies migrations (CI/CD)

# database-first (scaffold)
dotnet ef dbcontext scaffold "Server=.;Database=Legacy;Trusted_Connection=True;TrustServerCertificate=True" \
    Microsoft.EntityFrameworkCore.SqlServer -o Models --context LegacyContext
  • Migrations are C# classes with Up() and Down(); review them — renames may be generated as drop + add (data loss).
  • In production prefer idempotent scripts or bundles applied by the pipeline over Database.Migrate() at app start (race conditions with multiple instances, permissions).