liveBook · Manning

Dbcontext

As explained in Pro ASP.NET Core 7, Tenth Edition

DbContext is the Entity Framework Core base class that provides database access, entity tracking, and persistence services for a data context.

DbContext is the Entity Framework Core base class for an application's database context. Derive a context class from it, pass DbContextOptions to the base constructor, and expose DbSet properties for the entity types the application reads and writes. section 7.2.3 section 18.2.2

Listing 7.16 The contents of the StoreDbContext.cs file in the SportsStore/Models folder
using Microsoft.EntityFrameworkCore;

namespace SportsStore.Models {
   public class StoreDbContext : DbContext {
       
       public StoreDbContext(DbContextOptions<StoreDbContext> options)
           : base(options) { }
                       
       public DbSet<Product> Products => Set<Product>();
   }
}

StoreDbContext shows the minimal pattern: a constructor accepting configured options and a Products property backed by Set<Product>(). section 7.2.3

Register the context in Program.cs with AddDbContext. Its options select the database provider through UseSqlServer and obtain a connection string from ASP.NET Core configuration. That setup makes the context available as a service to request handlers. section 7.2.4 section 17.5.3

Listing 7.17 Configuring Entity Framework Core in the Program.cs file in the SportsStore folder
using Microsoft.EntityFrameworkCore;
using SportsStore.Models;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();

builder.Services.AddDbContext<StoreDbContext>(opts => {
    opts.UseSqlServer(
        builder.Configuration["ConnectionStrings:SportsStoreConnection"]);
});

var app = builder.Build();

app.UseStaticFiles();
app.MapDefaultControllerRoute();

app.Run();

The Program.cs listing connects StoreDbContext to SQL Server using the SportsStoreConnection configuration value. section 7.2.4

Read a result, then persist a missing one

An endpoint receives CalculationContext, looks up a Calculation by Count, and computes the total if none is found. It adds the new object to Calculations and calls SaveChangesAsync(). SQL logging shows the resulting SELECT and INSERT; without response or data caching, each request makes another query. section 17.5.6 section 17.5.2

Related-data queries need care in web APIs. Entity Framework Core can populate navigation properties using objects created by the same context. An Include query for a supplier's products can therefore also give each product a reference back to its supplier; serializing that object graph as JSON raises an object-cycle exception. In this ASP.NET Core example, a new context object is created for each HTTP request. section 20.2

For query troubleshooting, EnableSensitiveDataLogging can reveal parameter values that normal Entity Framework Core logs omit. Use it cautiously: logs may be accessible to people who should not see the application's sensitive data. section 17.5.6

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Builds and configures derived contexts, then demonstrates querying and saving; does not detail DbContext internals.
Examples
Uses product and calculation contexts, a calculation endpoint, SQL logs, and a supplier query that triggers an object-cycle exception.
What it assumes
Assumes C# classes and ASP.NET Core application setup while showing context construction and registration explicitly.
What you can do after
Build it from scratch: define a derived context, register its SQL Server connection, and use it to query and save entities.
How it connects
Connects DbSet, dependency injection, SQL Server configuration, navigation properties, and JSON serialization.

Also explained in

Compare how 4 books explain dbcontext →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.