Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 41 ยท DbContext and Models

DbContext and DbSet Explained

Understand the EF Core DbContext and DbSet - what they represent, how the model is built, why contexts are short-lived, and how to use factories, Find and the Set method correctly.

The DbContext is the heart of EF Core. It is your gateway to the database, the owner of the model, and the unit of work: it tracks the entities you load, collects your changes and writes them back when you call SaveChanges. Every DbSet<T> on it is a handle for one entity type, the thing you query and add to.

Most bugs that beginners hit (stale data, "a second operation started", memory growth, entities that "disappear") come from misunderstanding how long a context should live and what it remembers. This lesson explains both, with real code and a runnable stand-in of a unit of work.

What a context is

A DbContext is a lightweight, short-lived object. It does four jobs:

  1. Holds the model (the description of entities, keys, relationships), built once per context type and cached.
  2. Provides DbSet<T> properties to query and add.
  3. Runs the change tracker, which remembers loaded entities and their original values.
  4. Exposes SaveChanges, which turns tracked changes into commands inside one transaction.
C#
public class ShopContext(DbContextOptions<ShopContext> options) : DbContext(options)
{
    public DbSet<Customer> Customers => Set<Customer>();
    public DbSet<Order> Orders => Set<Order>();
    public DbSet<Product> Products => Set<Product>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // fluent configuration goes here (next lessons)
    }
}

Set<T>() returns the same DbSet<T>; writing the properties as => Set<Customer>() keeps nullable warnings quiet without = null!. A DbSet<T> property is optional for types that are only reachable through relationships, but it makes the entity discoverable and queryable from the context.

Lifetime: one unit of work, then throw it away

A context is cheap to create (the model is cached) and expensive to keep. Keep it for one unit of work: a web request, a message handler, one button click.

  • Not thread-safe. Never share one instance between threads or run two operations on it at once. The classic error is "A second operation was started on this context instance before a previous operation completed", caused by a missing await.
  • Tracking grows. A long-lived context keeps every loaded entity in memory and slows down as the tracker fills.
  • Stale data. A context returns already-tracked instances for rows it has seen, so a long-lived one shows old values.

In ASP.NET Core, AddDbContext gives you one per request. In places with no request scope (background workers, Blazor Server components, tests), inject a factory:

C#
builder.Services.AddDbContextFactory<ShopContext>(o => o.UseSqlite("Data Source=shop.db"));

public class ReportService(IDbContextFactory<ShopContext> factory)
{
    public async Task<int> CountOrdersAsync()
    {
        await using var db = await factory.CreateDbContextAsync();
        return await db.Orders.CountAsync();
    }
}

A DbContext is a unit of work

Load Query and track
Change Edit objects
Save One transaction
Dispose Then discard

Short-lived by design

1 / 2

Working with a DbSet

A DbSet<T> is both a query source and a collection-like object:

C#
var all = await db.Customers.ToListAsync();               // query
var one = await db.Customers.FindAsync(5);                // by primary key
db.Customers.Add(new Customer { Name = "Ada" });          // mark Added
db.Customers.Remove(one!);                                // mark Deleted
db.Customers.AddRange(newCustomers);                      // several at once
await db.SaveChangesAsync();                              // write everything

Find is special: it checks the change tracker first and only queries the database if the entity is not already tracked. FirstOrDefault(c => c.Id == 5) always runs a query. Use Find for a primary-key lookup and LINQ for everything else.

Inspecting the model

You can ask a context what it knows:

C#
foreach (var entityType in db.Model.GetEntityTypes())
{
    Console.WriteLine($"{entityType.ClrType.Name} -> {entityType.GetTableName()}");
}

db.Model.ToDebugString() prints the whole model in text form, which is a great tool when a convention does something unexpected.

Stand-in: a unit of work with tracking

This stand-in is not EF Core. It models the shape of a context: it tracks entities with a state, and SaveChanges applies only what changed. Run it and watch which operations are reported.

C# Stand-in: a unit of work and entity states

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The "second save" reports zero changes: after saving, the tracker's snapshot matches the current values again. That is exactly how EF Core's snapshot change tracking behaves (change tracking gets its own chapter later).

Stand-in: why a shared context is risky

C# Stand-in: stale data in a long-lived context

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The fix is not clever caching but a short lifetime: create a new context per unit of work.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which describes the right lifetime of a DbContext?

    Contexts are short-lived units of work. AddDbContext uses a scoped (per request) lifetime.
  2. 2. What is the difference between Find and FirstOrDefault(x => x.Id == id)?

    Find looks in the tracker by primary key first and queries only on a miss.
  3. 3. What typically causes 'A second operation was started on this context instance'?

    A context is not thread-safe; concurrent operations on one instance throw this error.
  4. 4. When would you inject IDbContextFactory instead of the context?

    A factory lets you create and dispose short-lived contexts yourself where DI scoping does not fit.

Summary

  • DbContext holds the model, the DbSet<T> handles, the change tracker and SaveChanges.
  • It is a short-lived unit of work and is not thread-safe.
  • Use AddDbContext per request and AddDbContextFactory for background work.
  • Find uses the tracker; LINQ queries always hit the database.
  • db.Model lets you inspect what EF Core inferred.

Next: Entity Classes and Conventions