DbContext & DbSet in EF Core

The #1 reason EF Core crashes in production. 5 mins.

Your First "Aha" Moment: DbContext is NOT your database. It's a short-lived work session.

1. What is DbContext? The Zomato Analogy

DbContext = Waiter at restaurant.

1. You sit down = New request starts โ†’ New DbContext created.
2. You order = _db.Users.Add() โ†’ Waiter notes it. Doesn't run to kitchen yet.
3. You say "Done" = SaveChanges() โ†’ Waiter sends all orders to kitchen in 1 trip.
4. You leave = Request ends โ†’ Waiter forgets you. DbContext disposed.

Rule: 1 HTTP request = 1 DbContext. Never reuse across requests.

2. DbSet = Your Table

public class AppDbContext : DbContext
{
    public DbSet Users { get; set; } // Users table
    public DbSet Orders { get; set; } // Orders table
}

Query it: _db.Users.Where(u => u.IsActive) โ†’ EF translates to SQL.

3. Register It Right - Or Crash in Prod

Program.cs

builder.Services.AddDbContext(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));

Default lifetime = Scoped. Perfect. New DbContext per request.

Career-Killer Mistake #1: AddSingleton<AppDbContext>()
What happens: Same DbContext for all users. User A loads data. User B sees User A's data. ChangeTracker grows forever. Memory leak. App crashes after 2 hours.
Never use Singleton. Use AddDbContext = Scoped by default.
Stop Here. Think. DbContext is cheap to create. Don't cache it. Don't make it static.
Next: OnModelCreating. That's where you fix EF's dumb defaults like nvarchar(max).

Quick Check ๐Ÿง 

Ready for Migrations? You mastered DbContext lifetime. Next: Migrations teaches Add-Migration, Script-Migration for DBAs, and rollback when you deploy bad schema. Let's go โ†’

Comments on DbContext & DbSet (0)

No comments yet. Be the first to share your thoughts!