advanced

Unit of Work

Track changed objects and commit them as one business transaction with explicit ordering and rollback behavior.

Unit of Work tracks loaded and changed entities, then flushes inserts, updates, and deletes as one coherent commit. It pairs well with an identity map inside a request or transaction scope.

					Request scope
  Identity map: row id → entity instance
  Unit of Work: new | dirty | deleted sets
  flush() → ordered SQL in one transaction
				

On interviews: discuss change tracking, flush timing, cascading, transaction scope, and how hidden flushes can surprise API handlers.

Common pitfalls: long-lived units of work holding stale state and memory; implicit flush at unexpected points; assuming every property write immediately hits the database.

The trade-off is convenient object graphs versus explicit control over when SQL runs.

Checklist:

  • Know when changes are tracked.
  • Know when SQL is emitted.
  • Keep request and transaction scope controlled.
  • Flush deliberately before returning responses.