A DbContext is the database-session abstraction between an ASP.NET Core application and its database. It lets C# code work with entities and perform CRUD operations. In a board-game API, an ApplicationDbContext provides access to board games, domains, mechanics, and their relationships. section 4.3.3
Listing 4.1 ApplicationDbContext.cs file
using Microsoft.EntityFrameworkCore;
namespace MyBGList.Models
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(
DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// TODO: custom code here
}
}
}
Start by deriving ApplicationDbContext from DbContext. Its constructor passes DbContextOptions<ApplicationDbContext> to the base class; OnModelCreating is the place for model-wide configuration. section 4.3.3
EF Core can map a model through conventions, data annotations, or the ModelBuilder Fluent API. Use DbSet properties to expose entity sets, and use OnModelCreating when a mapping needs explicit rules, such as a join entity’s composite key. Fluent API rules take precedence over data annotations, which take precedence over conventions. section 4.3.3
To put the context to work in the API:
- Register ApplicationDbContext in Program.cs with AddDbContext, configuring UseSqlServer with the DefaultConnection connection string. section 4.3.4
- Inject ApplicationDbContext into a controller constructor and keep the reference available to its action methods. section 5.2
- Query a DbSet in an action method. Calling ToArray() on the board-game query executes a database SELECT and returns an array of BoardGame entities instead of dummy data. section 5.2
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection"))
);
This registration connects the context to SQL Server using a named connection string supplied through configuration. section 4.3.4
Treat a context instance as one unit of work: a set of database operations for a business transaction. In a typical web API, that work fits within one HTTP request and response. The controller can obtain the context through dependency injection rather than constructing its own database session. section 4.3.4 section 5.2



