Reputation: 32946
Is this the correct way to use a transaction scope:
I have an object which represents part of a thing:
public class ThingPart
{
private DbProviderFactory connectionFactory;
public void SavePart()
{
using (TransactionScope ts = new TransactionScope()
{
///save the bits I want to be done in a single transaction
SavePartA();
SavePartB();
ts.Complete();
}
}
private void SavePartA()
{
using (Connection con = connectionFactory.CreateConnection()
{
con.Open();
Command command = con.CreateCommand();
...
command.ExecuteNonQuery();
}
}
private void SavePartB()
{
using (Connection con = connectionFactory.CreateConnection()
{
con.Open();
Command command = con.CreateCommand();
...
command.ExecuteNonQuery();
}
}
}
And something which represents the Thing:
public class Thing
{
private DbProviderFactory connectionFactory;
public void SaveThing()
{
using (TransactionScope ts = new TransactionScope()
{
///save the bits I want to be done in a single transaction
SaveHeader();
foreach (ThingPart part in parts)
{
part.SavePart();
}
ts.Complete();
}
}
private void SaveHeader()
{
using (Connection con = connectionFactory.CreateConnection()
{
con.Open();
Command command = con.CreateCommand();
...
command.ExecuteNonQuery();
}
}
}
I also have something which manages many things
public class ThingManager
{
public void SaveThings
{
using (TransactionScope ts = new TransactionScope)
{
foreach (Thing thing in things)
{
thing.SaveThing();
}
}
}
}
its my understanding that:
ThingPart.SavePart
(from outside the context of any other class) then part A and B would either both be saved or neither would be. Thing.Save
(from outside the context of any other class) then the Header and all the parts will be all saved or non will be, ie everything will happen in the same transaction ThingManager.SaveThings
then all my things will be saved or none will be, ie everything will happen in the same transaction.DbProviderFactory
implementation that is used, it shouldn't make a differenceAre my assumptions correct?
Ignore anything about object structure or responsibilities for persistence this is an example to help me understand how I should be doing things. Partly because it seems not to work when I try and replace oracle with SqlLite as the db provider factory, and I'm wondering where I should spend time investigating.
Upvotes: 2
Views: 2568
Reputation: 107327
Answering your bullets (and I've assumed Microsoft SQL Server 2005 or later):
Connections will not be new and reused from the pool
Just one gotcha - new TransactionScope() defaults to isolation level READ_SERIALIZABLE - this is often over pessimistic for most scenarios - READ COMMITTED is usually more applicable.
Upvotes: 3