Saturday, April 4, 2026

EF | Code Vs Database First

Code First

What it is:

You write C# classes first, and EF generates the database from them.

Example:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}

Then EF creates a table like:
- Id
- Name
Products

How it works:
  • Define models (classes)
  • Use migrations to create/update DB
  • EF syncs code → database

Pros:
  • Full control in code
  • Version control friendly (migrations)
  • Great for new projects
  • Clean and flexible

Cons:
  • Requires migration management
  • Not ideal for complex existing DBs

Database First

What it is:
You design the database first, and EF generates C# classes from it.

Workflow:
  • Create tables in DB (SQL Server, etc.)
  • Scaffold models using EF
Scaffold-DbContext "connection_string" Microsoft.EntityFrameworkCore.SqlServer

How it works:
  • Existing DB → generate models
  • EF reads schema and creates classes

Pros:
  • Best for existing/legacy databases
  • DB controlled by DBAs
  • No need to design schema in code

Cons:
  • Harder to maintain changes
  • Regenerating models can overwrite changes
  • Less control compared to Code First

Key Differences

FeatureCode FirstDatabase First
Starting pointC# classesDatabase
ControlDeveloper (code)Database
Schema updatesMigrationsDB changes + re-scaffold
Best forNew projectsExisting databases
FlexibilityHighModerate

When to Use What?

Use Code First:
  • Building a new application
  • Agile development (frequent changes)
  • You want everything in code

Use Database First:
  • Working with existing DB
  • DB already designed/managed
  • Large enterprise systems

Simple Analogy
  • Code First = Write blueprint → build house 
  • Database First = House exists → create blueprint 

Final Takeaway

Modern development (especially with Entity Framework Core):

  • Mostly prefers Code First + Migrations
  • But Database First is still very useful for real-world legacy systems

---------------------------------------------------------------------------------------------------

How to Update DB When Classes Change?

When you modify your C# models (add property, remove property, new class, etc.), you don’t directly update the database.

Instead, you use Migrations.


Step-by-step

1. Change your model
public class Product
{
public int Id { get; set; }
public string Name { get; set; }

// NEW FIELD
public decimal Price { get; set; }
}

2. Add a Migration

Add-Migration AddPriceToProduct

EF generates a migration file like:

migrationBuilder.AddColumn<decimal>(
name: "Price",
table: "Products",
nullable: false,
defaultValue: 0m);

3. Update Database
Update-Database

This applies changes to DB.


What Happens to Existing Data?

Good news: Data is usually retained

EF migrations are incremental, not destructive (unless you explicitly make them so).


Case-by-case behavior

➤ Adding a new column
  • Existing data stays
  • New column gets:
    • Default value OR
    • NULL (if nullable)
public decimal? Price { get; set; } // nullable → safe

➤ Adding NON-nullable column
  • Must provide default value OR migration will fail
public decimal Price { get; set; } // requires default

➤ Renaming a column

EF might:

  • Drop old column ❌
  • Create new column ❌

👉 This can cause data loss unless handled manually.

✔ Fix:

migrationBuilder.RenameColumn(
name: "OldName",
table: "Products",
newName: "NewName");


Note: Using rename retain the column data

➤  Deleting a property
  • Column is dropped → data lost

➤  Adding a new table (new class)
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
}

👉 Migration will:

  • Create new table
  • Existing tables/data remain unchanged

3. How EF Keeps Track

EF uses a special table:

👉 __EFMigrationsHistory

  • Tracks applied migrations
  • Ensures only new changes are applied

4. Best Practices

1. Always use migrations

Never manually change DB in Code First workflow


2. Make new fields nullable initially
public string? NewColumn { get; set; }

Then later enforce required


3. Review migration code before applying

Check for:

  • Drops ❌
  • Renames ❌
  • Data loss risks

4. Use Rename instead of Drop/Create

Prevents data loss


5. Backup DB in production

Always before running:

Update-Database

5. Simple Flow Summary
Change Model → Add-Migration → Review Migration → Update-Database

Key Takeaway
  • EF does NOT overwrite DB
  • It applies incremental schema changes
  • Existing data is safe unless you explicitly break it

No comments:

Post a Comment

Node | Cluster Vs Worker Threads

Cluster: Multiple processes (scale app across CPU cores) Worker Threads: Multiple threads (handle CPU-heavy work inside one process) Cluster...