简体   繁体   中英

What is the Best Practice for creating transactions with multiple objects with Enterprise Library 5.0

Background:

I have an object that has a number of properties that are other objects. On Save of the main object, I insert a record into the database and then call the Save method of the on the sub objects. The current risk in this model is that if the main object is saved to the database, but one of the sub-objects are not, then the data will not reflect an accurate state.

My .NET 4.0 application uses Enterprise Library 5.0 and the data is stored in one SQL Server 2008 database. I would like to implement transaction support so that either all the objects are saved when all saves are successful, or rolled back on failure.

Question:

I found a good but dated article about Transaction support in .NET 2.0 vs .NET 1.0/1.1 but wanted to know what the current best practice is to implement transaction support.

I ended up going with System.Transactions.TransactionScope as outlined in the article referenced above. Enterprise Library 3.0 and higher looks for Transaction.Current when connecting to the database. You don't have to explicitly pass transaction information.

using(TransactionScope scope = new TransactionScope())
{
   /* Perform transactional work here */
   //No errors-commit transaction
   scope.Complete();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM