Explain Code First vs Database First approaches.

4 minintermediateEF-Corecode-firstdatabase-first

Quick Answer

Code First defines the model as C# classes and generates/evolves the database schema via migrations — ideal for greenfield, source-controlled schemas. Database First reverse-engineers entity classes from an existing database using scaffolding. EF Core is primarily Code First (migrations-driven) but supports scaffolding from an existing DB; choose based on whether the model or the database is your source of truth.

Detailed Answer

Code First Approach:

  • Define your domain model classes first
  • EF generates the database schema from your code
  • Uses migrations to evolve the database
  • Better for new projects and version control
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

public class AppDbContext : DbContext
{
    public DbSet Products { get; set; }
}

// Generate migration: dotnet ef migrations add InitialCreate
// Update database: dotnet ef database update

Database First Approach:

  • Start with an existing database
  • Generate entity classes from the database
  • Uses scaffolding to create models
  • Better for existing databases
# Scaffold from existing database
dotnet ef dbcontext scaffold "ConnectionString" Microsoft.EntityFrameworkCore.SqlServer -o Models

When to use each:

  • Code First: New projects, agile development, domain-driven design
  • Database First: Legacy databases, DBA-controlled schemas, multiple applications sharing one database