Tutorials Entity Framework Core Tutorial
DbContext in EF Core — Complete Guide
DbContext in EF Core — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of Entity Framework Core Tutorial on Toolliyo Academy.
On this page
Entity Framework Core Tutorial · Lesson 5 of 100
DbContext in EF Core
Beginner → Intermediate → Advanced → Professional
Beginner · 1 — Foundations · ~6 min · Module 1: EF Core Fundamentals
What is this?
DbContext is the main class for database work in EF Core. It exposes DbSet properties, tracks changes, and commits work through SaveChangesAsync.
Why should you care?
ShopNest services should not open SqlConnection everywhere. One ShopNestDbContext per request centralizes configuration, tracking, and transactions.
See it live — copy this example
Paste into a .NET project with EF Core packages, then run with LocalDB/SQL Server (dotnet ef / dotnet run).
public class ShopNestDbContext : DbContext
{
public ShopNestDbContext(DbContextOptions<ShopNestDbContext> options)
: base(options) { }
public DbSet<Product> Products => Set<Product>();
public DbSet<Order> Orders => Set<Order>();
public DbSet<Customer> Customers => Set<Customer>();
}
What happened?
- Inheriting DbContext gives you Set
() and change tracking. - The constructor receives options (connection, provider) injected from DI at startup.
Practice next
- Add ShopNestDbContext to ShopNest.Infrastructure.
- Register AddDbContext in Program.cs with your LocalDB connection string.
- Resolve ShopNestDbContext in a minimal API endpoint and call Database.CanConnectAsync().
- Override OnConfiguring only for design-time fallback — prefer DI options in production.
- Add DbSet
and run dotnet build to see compile-time safety.
Remember
DbContext is the EF session object. DbSet properties map to tables. Register as Scoped in web applications.
ShopNest scoped data session
Checkout controller receives ShopNestDbContext via constructor injection for the duration of one HTTP request.
Outcome: Connection and tracker lifetime align with a single customer action.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!