Database Transactions
All updates to an ice.NET database repository must per performed
inside a transaction scope. The transaction ensures that the result
of the update are persisted to the database only if the whole transaction
has been successfully completed. It also helps to ensure the consistency
of data accessed by concurrent sessions.
Any attempt to call a updating method or property outside a transaction scope
results in a DatabaseException thrown by the platform.
Examples
This example shows how to use an ITransactionContext
to implement an atomic, exception-safe transaction scope.
using (ITransactionContext pTransaction = Repository.BeginTransaction())
{
try
{
// [do some updates, throw exception on failure]...
// Transaction sucessfully completed...
pTransaction.Commit();
}
catch
{
// Transaction failed...
pTransaction.Rollback();
throw;
}
}
To simplify the usage of transactions, the IDatabaseRepository provides
a convenience method IDatabaseRepository.ExecuteTransaction that
encapsulates the ITransactionContext handling.
This example shows how to use the IDatabaseRepository.ExecuteTransaction
convenience method to implement an atomic, exception-safe transaction scope.
Repository.ExecuteTransaction(delegate()
{
// [do some updates, throw exception on failure]...
});
The commit/rollback handling is done automatically based on wether the
IDatabaseRepository.ExecuteTransaction scope is exited
regularly or with an exception.
Transactions and Business Objects
Business objects implementations should not actively refer to transaction management.
It should always be the calling environment (service, user interface) that defines the scope
of a transaction. This is crucial to ensure the usefulness of the business objects
in a variety of application cases, not only in the context of a particular business
transaction.
By throwing an exception, the business objects implementation can indicate that something
went wrong that prevents the encapsulating transaction from being successfully comitted.
The transaction itself will be then rolled back as a whole by the calling scope.
In-memory processing
This information about transactions applies to database repositories only.
When accessing the in-memory repository implementation (by retrieving an IRepository
reference from IInProcRepositoryFactory), transaction management is
not available. The transaction management methods are defined in IDatabaseRepository.
However, this does not affect the applicability of business objects in arbitrary
repository environments, because the business objects refer to the IRepository
interface only and do/should not contain any active transaction handling themselves.