What is the difference between Code First and Database First?
Quick Answer
Code First: you write the C# entity classes and configuration, and EF generates the database schema through migrations. Database First: the database already exists and you scaffold (reverse-engineer) the entity classes and DbContext from it. EF Core supports both; Code First with migrations is the common choice for new projects.
With Code First I define the entity classes and the mapping in C#, and EF creates and evolves the database schema for me through migrations. With Database First the schema already exists, and I scaffold the entities and DbContext out of it with the ef dbcontext scaffold command. New projects usually go Code First because the migrations live in source control and get reviewed like any other code. Database First makes sense when a DBA team owns the schema or I'm working against a legacy database. EF Core doesn't have the old EDMX designer, so it's really just those two.
- Code First
- Model is the source of truth; schema is derived.
- Schema changes are versioned migrations, reviewable in pull requests.
- Great for greenfield projects and teams that own the database.
- Database First (scaffolding)
- Run
dotnet ef dbcontext scaffoldagainst the connection string to generate entities + context. - Fits when a DBA team owns the schema, or you're integrating with a legacy database.
- Re-scaffolding overwrites customisations unless you use partial classes or the design-time hooks.
- Run
EF Core has no visual EDMX “Model First” designer like EF6. In practice many teams do Code First but occasionally scaffold a view or a legacy table. The mental model is the same either way once the classes and DbContext exist.