[TOC]

What’s UOW?

“A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you’re done, it figures out everything that needs to be done to alter the database as a result of your work.” – Martin Fowler

SO Unit of Work Key Info:

  • UOW keeps track of changes
  • UOW maintenance change list
  • UOW commits all changes at once

EF Core DbContext naturally UOW is realized

  • Each DbContext instance has a ChangeTracker that tracks changes to the entity

  • When DbContext.SaveChanges is called, all changes are committed to the database in one go via the transaction

Implementing Repository pattern in domain-driven Design,By UOW UnitOfWorkInterceptor took over after ApplicationServervice methods performed DbContext. SaveChanges operation

The transaction is just a way to realize the unit of work. EFCore can implement UOW without using transactions.

What’s Ambient Transactions?

Common Transaction:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using (var context = new ApplicationDbContext())
{
using (var transaction = context.Database.BeginTransaction())
{
var student1 = new Student();
student1.Name = "Robert Fatou";
context.Add(student1);
context.SaveChanges();
// The Id will have a valid value
Console.WriteLine(student1.Id);
// Let's revert the operation
transaction.Rollback();
}
}

Ambient Transaction:

An ambient transaction is one that works at the thread level. Thus, all operations that occur in that context will be part of the transaction.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
static void Main(string[] args)
{
using (var scope = new TransactionScope())
{
CreateStudent();
CreateCourse();
// Uncomment the following line if you want to
// have the previous operations persisted in the Database
//scope.Complete();
}
}

private static void CreateCourse()
{
using (var context = new ApplicationDbContext())
{
var course = new Course();
course.Name = "Programming I";
context.Add(course);
context.SaveChanges();
}
}

private static void CreateStudent()
{
using (var context = new ApplicationDbContext())
{
var student1 = new Student();
student1.Name = "Transaction Scope";
context.Add(student1);
context.SaveChanges();
}
}

Reference:

P of EAA: Unit of Work (martinfowler.com)

DbContext Lifetime, Configuration, and Initialization - EF Core | Microsoft Learn

Transactions - EF Core | Microsoft Learn

Implementing an Implicit Transaction using Transaction Scope - .NET Framework | Microsoft Learn

Entity Framework Core 2.1: Ambient Transactions