liveBook · Manning

Dbcontext

As explained in ASP.NET Core in Action, 3e

DbContext is the Entity Framework Core base class that coordinates database connections, entity tracking, querying, and persistence for a data model.

A DbContext is your application’s way to configure Entity Framework Core (EF Core) and access a database at runtime. Define a class that inherits from DbContext, then use it to work with entity classes: .NET objects that EF Core maps to database tables. An application can have more than one DbContext, including contexts configured for different databases. section 12.1.4

Start with the entities you want to store. For a recipe API, a Recipe has a collection of Ingredients, and each Ingredient belongs to one Recipe. Expose Recipe through a DbSet<Recipe> property on the context. EF Core uses that property and the linked entity types to build its internal data model. By convention, properties such as RecipeId identify primary keys, while Ingredient.RecipeId helps define the relationship. section 12.1.4 section 12.2.2

Listing 12.3 Defining the application DbContext
public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options)   #1
        : base(options) { }                                       #1
    public DbSet<Recipe> Recipes { get; set; }                    #2
}

The small AppDbContext definition shows the two essentials: a constructor that passes DbContextOptions to the base class and a DbSet<Recipe> property. section 12.2.2

To put the context to work in an ASP.NET Core application:

  • Choose a database provider and install its EF Core NuGet package. Design the context and entities, then register the context with dependency injection using AddDbContext<T>, specifying the provider and connection string. section 12.2 section 12.6
  • Generate and apply a migration so the database schema matches the model. After changing the model, create another migration and apply it. section 12.2 section 12.6
  • Keep database access in a service rather than in minimal API endpoint handlers when you want to separate concerns and make the service testable. section 12.2

Update a recipe

Load a recipe with context.Recipes.FindAsync(id), change its properties, then call context.SaveChangesAsync(). FindAsync can return an entity already tracked by the context without querying the database. For loaded entities, EF Core tracks property values and uses changes to determine which columns to include in the UPDATE statement. Setting IsDeleted to true and saving follows the same pattern for the example’s delete operation. section 12.4.4

Two lifetime and model changes are worth watching. To add ASP.NET Core Identity entities, inherit from IdentityDbContext<ApplicationUser> instead of DbContext and create a migration. A DbContext is normally scoped; a singleton background service should create and dispose a scope each time it needs to resolve one, rather than inject the context into its constructor. section 23.4.2 section 34.1.2

How ASP.NET Core in Action, 3e covers it

How deep it goes
Works through context definition, registration, migrations, and tracked updates, while leaving detailed convention customization and alternative tracking mechanisms to documentation.
Examples
Uses a recipe-and-ingredient context, a tracked recipe update, an Identity context, and scoped access from a background service.
What it assumes
Starts with .NET entity classes and explains their table mapping, keys, and relationships before using the context.
What you can do after
Build it from scratch with EF Core by defining and registering a context, migrating its schema, and loading and saving entities.
How it connects
Links DbSet<T>, entity relationships, dependency injection, migrations, change tracking, and IdentityDbContext.

Also explained in

Compare how 4 books explain dbcontext →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.