I'm working on a WPF app which needs to perform a lot of updates and inserts during a particular operation. We are using Fluent Nhibernate 3.2. I want to execute all the updates and inserts in a single transaction so that if there's any error I can roll back all the steps. We have defined commands for each of the steps. The issue is that in one of the insert commands , we have used the Parallel.Foreach loop in which we create a new stateless session per thread.
Now if I wish to wrap all these commands in a transaction , how do I do that .?
We already have a UnitOfWork implemented , but it does not allow more than one session at a time. So I thought of moving away from the UnitOfWork and directly pass the Sessionfactory to each of the commands. Every command then creates its own session and executes it. We have a command processor which executes all the commands :
public class CommandProcessor : ICommandProcessor
{
public void ExecuteCommands ( IEnumerable<ICommand> commands)
{
using (var scope = new TransactionScope(TransactionScopeOption.Required))
{
foreach (var command in commands)
{
command.Execute(UnitOfWork.UnitOfWorkFactory.SessionFactory);
}
scope.Complete();
}
}
}
The transaction scope doesn't seem to work as I get an error "The operation is not valid for the state of the transaction".
Is this the correct usage of the transaction scope ? Any suggestions on how I could progress ?
Thanks.