Skip to content

Module 1: EF Core (The Warehouse)

📚 Module 1: EF Core (The Warehouse)

Focus: Moving from “Classes” to “Databases.”

In .NET, we almost never write raw SQL. We use Entity Framework Core (EF Core). It’s a tool that translates your C# objects into database tables automatically.


🏗️ Step 1: The DbContext (The “Warehouse Manager”)

The DbContext is the most important part of your data layer.

🧩 The Analogy: The Inventory Log

Imagine you are managing a warehouse.

  • The Products: Your C# classes (e.g., Product or Customer).
  • The DbContext: The giant logbook where you track every item in the warehouse.
  • The Change Tracker: The person who notices when you move an item or change a price, so they can update the database at the end of the day.

How it looks in code:

public class StoreContext : DbContext {
    public DbSet<Product> Products { get; set; }
    public DbSet<Customer> Customers { get; set; }
}

🏗️ Step 2: Migrations (The “Time Machine”)

When you change your C# class (e.g., you add a Price property to your Product), you need to tell the database.

🧩 The Analogy: The Renovation Blueprint

  • Your Code: The new blueprint for the store.
  • The Migration: The step-by-step instructions for the builder.
  • The Process:
    1. “Add a new shelf for the prices.”
    2. “Move the old items to the new shelf.”
    3. “Finish the renovation.”

Why do we do this? So you can always roll back to an older version if you make a mistake.


🏗️ Step 3: LINQ (The “Search Engine”)

How do we find a specific product? We use LINQ (Language Integrated Query).

🧩 The Analogy: The Smart Librarian

You tell the librarian (LINQ): “Hey, can you give me all the books written in 2024?”

  • In Code: var recentBooks = context.Books.Where(b => b.Year == 2024).ToList();

The magic: LINQ is written in C#, but it gets translated into SQL automatically by EF Core.


🧪 Step 4: Your First Migration

Run these commands in your terminal to set up a database:

# 1. Create a migration (The instructions)
dotnet ef migrations add InitialCreate

# 2. Update the database (The renovation)
dotnet ef database update

🥅 Module 2 Review

  1. EF Core: The bridge between C# and SQL.
  2. DbContext: The manager that tracks your data.
  3. DbSet: A representation of a single table in your database.
  4. Migrations: The version control for your database schema.
  5. LINQ: The easy way to search data without writing raw SQL.