Entity Framework Core Mastery

Setup and DbContext Integration

1 Views Updated 5/4/2026

Setup and DbContext Integration

The DbContext is the absolute heart of Entity Framework Core. It represents a living session with the database. It is responsible for establishing the network connection, maintaining the Change Tracker, executing SQL, and marshaling data mapped to DbSet properties.

1. Creating the ApplicationDbContext

You must inherit from Microsoft's base DbContext class. Every table you want to query must be exposed as a DbSet<TEntity> property.

using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : DbContext
{
    // The constructor accepts connection options from Program.cs
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) 
        : base(options)
    {
    }

    // These properties map directly to physical database tables
    public DbSet<User> Users { get; set; }
    public DbSet<Product> Products { get; set; }
    public DbSet<Order> Orders { get; set; }
}

2. Connecting the Database Securely

You should NEVER hardcode connection strings (Passwords, Server IPs) directly into the C# source code. They must be stored in configuration files or Environment Variables.

Step 1: appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=ECommerceDb;User Id=sa;Password=SuperSecret!;TrustServerCertificate=True;"
  }
}

Step 2: Injecting into the Pipeline (Program.cs)

var builder = WebApplication.CreateBuilder(args);

// Grab the secure string
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

// Register the DbContext into the Dependency Injection container
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
    // Instruct EF Core to use the SQL Server provider package
    options.UseSqlServer(connectionString);
});

3. The Global Singleton Anti-Pattern

A fatal junior mistake is attempting to create a single DbContext and keeping it alive for the entire lifespan of the application (Singleton). DbContext is explicitly designed to be short-lived. It accumulates memory in its Change Tracker. If used as a Singleton on a web server, it will track thousands of objects until the server runs out of RAM and crashes with an OutOfMemoryException.

The Enterprise Standard: When you use AddDbContext, ASP.NET Core registers it as Scoped by default. This means a brand new DbContext is instantiated for every HTTP Request, executes the logic, and is safely destroyed and garbage collected the second the HTTP Request ends.

4. Interview Mastery

Q: "If 10,000 users hit our API simultaneously, `AddDbContext` will frantically instantiate and destroy 10,000 `ApplicationDbContext` objects in memory per second. How do we prevent CPU exhaustion and Garbage Collection locking under extreme loads?"

Architect Answer: "We use `AddDbContextPool`. Instantiating a DbContext is somewhat heavy computationally because it has to initialize internal Dictionaries and state machines. By switching to `builder.Services.AddDbContextPool(...)`, EF Core creates a persistent thread-safe pool of recycled DbContexts. When an HTTP Request ends, instead of aggressively garbage collecting the DbContext, EF Core 'cleans' it by wiping its change tracker, and places it back into the Pool. The next incoming HTTP Request simply borrows a pre-initialized DbContext from the Pool, resulting in massive CPU savings and near-zero Garbage Collection overhead."

Entity Framework Core Mastery
1. Foundations & Architecture
Introduction to Object Relational Mapping (ORM) Entity Framework Core Architecture & Providers Setup and DbContext Integration Code-First vs Database-First Approaches Reverse Engineering Existing Databases (Scaffolding)
2. Code-First Modeling
Entity Conventions & Data Annotations The Fluent API Deep Dive (OnModelCreating) Primary Keys, Composite Keys, & Guids Required Properties & Database Defaults Value Conversions (Enums & Strongly Typed IDs)
3. Relational Architecture
One-to-Many Relationships & Foreign Keys One-to-One Relationships (Dependent Entities) Many-to-Many Relationships & Navigation Properties Owned Entity Types (Value Objects) Table-per-Hierarchy (TPH) Inheritance
4. Data Querying & LINQ
Basic LINQ Queries & IQueryable Execution Tracking vs No-Tracking Queries (Performance) Eager Loading vs Explicit Loading (Include) Lazy Loading Pitfalls & Proxies Client vs Server Evaluation Parsing
5. Manipulating Data (CUD)
Adding, Updating, and Removing Entities The ChangeTracker and Entity States Disconnected Entities in Web APIs Batch Updates and Deletes (.NET 7+)
6. Advanced Performance & Scale
Concurrency Tokens and Optimistic Locking Raw SQL Queries and Views (FromSqlRaw) Compiled Queries for High Throughput Interceptors (Logging & Auditing Data Changes) DbContext Pooling Mechanisms Managing Complex EF Core Migrations (CI/CD)