Home

unitofwork

Unit of Work is a design pattern that maintains a list of objects affected by a business transaction and coordinates the writing out of changes to the underlying data store. It tracks new, modified, and deleted objects, and ensures that all updates are committed or rolled back as a single atomic operation. By consolidating operations, it reduces the number of database calls and helps maintain data consistency across the domain model.

Origins and relationship: The pattern emerged as part of the patterns catalog for enterprise applications and

Implementation and examples: In many frameworks the Unit of Work is provided by the ORM layer. For

Benefits and caveats: Benefits include consistency, simpler rollback semantics, and reduced round-trips. Drawbacks include added complexity,

Related patterns and alternatives: The Unit of Work is often complemented by repositories and is related to

is
closely
associated
with
object-relational
mapping.
It
is
commonly
used
together
with
the
Repository
pattern:
repositories
provide
access
to
domain
entities,
while
the
Unit
of
Work
coordinates
changes
across
those
entities
and
applies
them
through
a
single
transaction.
example,
Entity
Framework's
DbContext
acts
as
a
Unit
of
Work
in
.NET
applications;
SQLAlchemy's
Session
serves
the
same
role
in
Python;
NHibernate's
ISession
similarly
coordinates
persistence.
A
typical
workflow
is
to
retrieve
or
create
entities
within
a
Unit
of
Work,
modify
them,
and
then
call
commit
or
dispose
to
flush
changes;
the
Unit
of
Work
maps
to
a
database
transaction.
risk
of
long-running
transactions,
and
potential
coupling
to
a
specific
ORM.
Proper
scoping
is
important
to
avoid
locking
and
performance
problems.
Command
Query
Responsibility
Segregation
and
event
sourcing
as
alternative
approaches
for
persisting
domain
changes.