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



