Advertisement
Intermediate .NET, Entity Framework Core & Data Access

What is the difference between EF Core's Code-First (migrations) approach and Database-First (scaffolding) approach?

Short answer

Code-First defines your data model as C# classes first, then uses migrations to generate and apply corresponding database schema changes -- ideal for new projects where the application drives the schema.

Save .NET mock interview
Advertisement
AModel answer
Code-First defines your data model as C# classes first, then uses migrations to generate and apply corresponding database schema changes -- ideal for new projects where the application drives the schema. Database-First (via `dotnet ef dbcontext scaffold`) instead reverse-engineers C# entity classes and a DbContext from an existing database schema, appropriate when integrating with a pre-existing database you don't control or fully own the schema for.
# Code-First: define classes, generate migrations
dotnet ef migrations add InitialCreate
dotnet ef database update

# Database-First: scaffold classes from existing DB
dotnet ef dbcontext scaffold "Server=...;Database=Legacy;" Microsoft.EntityFrameworkCore.SqlServer
Real-world example
A greenfield microservice uses Code-First migrations to evolve its schema alongside application development, while a reporting service connecting to a legacy, DBA-controlled data warehouse uses Database-First scaffolding to generate matching entity classes.
Likely follow-ups
  • How do you keep scaffolded classes in sync when the source database schema changes?
  • Can you mix both approaches within the same solution?
Related topics