To give an arbitrary example, let's say that I'm storing two objects, Item
and Box
, in the same database.
These objects have a one-to-one relationship.
Item
has the following properties:
- ID (string)
- BoxID (string)
- Price (int)
Box
has the following properties:
- ID (string)
- ItemID (string)
- ItemLastUpdated (timestamp)
Whenever Item
's price changes, Box
's ItemLastUpdated
must be updated as well:
try {
item.price = newPrice;
itemRepository.Save(item);
} catch (Exception e) {
// Handle the Exception.
}
try {
box.itemLastUpdated = now;
boxRepository.Save(box);
} catch (Exception e) {
itemRepository.RollbackLastChange();
// Handle the Exception.
}
My question concerns the scenario where a database outage causes boxRepository.Save()
to fail.
Because itemRepository
also uses the same database, it won't be able to rollback its last change.
item
's data is now bad because it has stayed modified despite needing a rollback.
EDIT:
Our current architecture cannot use transactions because it is using interfaces to work with databases and therefore cannot assume that a given database has transactions built-in.
If we assume that whatever database we use will have transactions, how do we recode the above code to use them? We are currently using different repositories to work with different tables.
Will creating a "master object" to collate all changes and attempt a transaction suffice, or is there a better way?