C# .NET: Use Transactions With Entity Framework to Rollback Data on Error

5/12/2014 5:58:35 PM

The following wraps Entity Framework calls in a transaction and will rollback all commits if an error occurs.

Transaction Levels:

http://msdn.microsoft.com/en-us/library/system.data.isolationlevel.aspx

using System.Transactions;

...

var userRepository = MySpecialCodeToGetUserRepo();

var transactionOptions = new System.Transactions.TransactionOptions();
//transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.Chaos;
transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
//transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
//transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.RepeatableRead;
//transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable;
//transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.Snapshot;
//transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.Unspecified;

//using (var transaction = new System.Transactions.TransactionScope()) - default constructor
using (var transaction = new System.Transactions.TransactionScope(TransactionScopeOption.Required, transactionOptions))
{
	try
	{
		for (int x = 1; x <= 100; x++)
		{			
			Entities.User newUser = new Entities.User();
			newUser.FirstName = "TestFirst";
			newUser.LastName = DateTime.Now.ToString();			
			
			userRepository.Add(newUser);
			
			//commit new user to db
			userRepository.SaveChanges();
		}

		//uncomment to force error and rollback transaction
		//int x = 0;
		//x = x / x;
			
		//if no errors occur, transaction will complete
		transaction.Complete();
	}
	catch
	{ 
		//if error is encountered, transaction.Complete() will never be called and transaction will rollback when we leave the transaction's context (outside of using)
	}
}