Both are Entity Framework approaches; the difference is which side is the source of truth: your C# model (Code First) or the existing database (Database First). Code First - You write entity classes and a DbContext; EF Core generates the schema through migrations. public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public decimal Price { get; set; } } dotnet ef migrations add AddProducts dotnet ef database update - Schema changes are versioned in source control with the code, reviewed in pull requests and applied in CI/CD. - Configuration through the Fluent API (OnModelCreating) or data annotations. When to choose Code First - New (greenfield) applications where the team owns the database. - Domain-driven design, where the domain model drives the schema. - Teams that want schema changes versioned and deployed with application code, and consistent environments (dev, test, prod). Database First - The database already exists (or is designed by DBAs); EF Core generates entity classes and the DbContext from it via scaffolding: dotnet ef dbcontext scaffold "Server=.;Database=Shop;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models - When the database changes, you re-scaffold (use partial classes for custom code so it is not overwritten) or update the model manually. EF Core Power Tools offers a convenient UI for this. - (The EDMX designer from classic Entity Framework 6 does not exist in EF Core.) When to choose Database First - Legacy or shared databases used by several applications, reporting tools or stored procedures. - Organisations where DBAs own and control schema changes. - Integrating with a third-party product's database. Hybrid approaches - Start with Database First scaffolding for an existing database, then switch to Code First migrations once the application owns the schema. - Use Code First but write migrations by hand for complex SQL (data fixes, indexes with special options). Practical considerations - Code First requires discipline with migrations: review generated SQL, avoid destructive changes, and use idempotent scripts or bundles for production. - Database First requires keeping the model in sync after every schema change. Interview summary: "I prefer Code First for new systems because schema changes are versioned and reviewed with code; I use Database First when integrating with an existing database owned by another team."
Ravindra Wadile · · 0 likes