liveBook · Manning

Database transaction

As explained in Building Web APIs with ASP.NET Core

A unit of work is a pattern that tracks objects affected by a business transaction and coordinates persisting their changes and resolving concurrency problems.

A database transaction is a unit of work: a set of CRUD operations performed during one business transaction. At the application level, it tracks affected objects, coordinates persistence, and helps resolve concurrency problems. section 4.3.4

In an ASP.NET Core API, one DbContext instance commonly represents one unit of work within a single HTTP request/response lifecycle. This arrangement supports the transaction’s atomicity, consistency, isolation, and durability properties. section 4.3.4

A typical request uses the transaction boundary as follows:

  • A controller receives an HTTP request and obtains ApplicationDbContext through dependency injection. section 4.3.4 section 5.2
  • The action builds a query against the context, which represents the requested database operation. section 5.2
  • Executing the query retrieves database records, creates entities, and returns them to the action for JSON serialization. section 4.3.4 section 5.2

Board-game retrieval

BoardGamesController stores an injected ApplicationDbContext in a private field. Its Get() action replaces manually generated data with a query against _context.BoardGames; ToArray() executes the query and returns the resulting BoardGame entities. section 5.2

builder.Services.AddDbContext<ApplicationDbContext>(options =>
   options.UseSqlServer(
       builder.Configuration.GetConnectionString("DefaultConnection"))
   );

Register ApplicationDbContext with dependency injection and configure it to use SQL Server, establishing the context used for request-scoped work. section 4.3.4

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Defines unit-of-work responsibilities and traces a read request, but does not detail write coordination or concurrency-resolution implementation.
Examples
Uses BoardGamesController, ApplicationDbContext, the BoardGames query, and ToArray() to demonstrate request-scoped retrieval.
What it assumes
Assumes an ASP.NET Core web API and database context, while introducing unit-of-work responsibilities and request-scoped context usage.
What you can do after
Apply it via ASP.NET Core dependency injection by querying a database through a controller’s ApplicationDbContext.
How it connects
Connects database transactions with DbContext, dependency injection, CRUD operations, ACID properties, and concurrency problems.

Also explained in

Compare how 14 books explain database transaction →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Web APIs with ASP.NET Core. The section links point to the parts of the book it draws on.