I read the following StackOverflow posts about nested transactionScope, but I couldn't get it to work in one of my integration tests. I wanted to insert some records into the database and verify the writes afterward immediately, and then rollback at the end of the test to its origin.
The problem is that I would need to explicitly call connection.EnlistTransaction(Transaction.Current)
in order to have it working. One thing that I am not sure about is whether everything has to be in the same layer or file, because in my case (code example on the bottom) the transaction scope is defined in the service tier, and it calls multiple downstream repository objects for low level SQL query operations (CRUD)
- TransactionScope error in ambient transaction does not rollback the transaction
- Under what circumstances is an SqlConnection automatically enlisted in an ambient TransactionScope Transaction?
- Introducing System.Transactions in the .NET Framework 2.0
Here's the code I've had so far
using(TransactionScope scope = new TransactionScope())
{
repository1.CreateEntries(expectedList);
repository2.UpdateEntries(expectedList);
scope.Dispose();
}
this is from repository1 class
void CreateEntries(List<Object> list) {
using (var conn = new SqlConection(CONNECTION_STRING))
{
conn.Open();
// i need to explicitly call this
conn.EnlistTransaction(Transaction.Current);
....
}
}
this is from repository2 class
void UpdateEntries(List<Object> list) {
using (var conn = new SqlConection(CONNECTION_STRING))
{
conn.Open();
conn.EnlistTransaction(Transaction.Current);
....
}
}