Reputation: 625
I trying to understand how I can make transactions work with my project. I use EntityFramework 4 with an Oracle 11g database.
Here his the deal, I have a lot of operation to do, and I want to roll back when an unexpected exception is thrown. I have multiple class with simples operation, each class create it's own Context and make some change, for example :
public class OneDaoFactory
{
public int AddTreatment(Dto dto)
{
using (Context bdd = new Context())
{
//Make some changes in database
bdd.SaveChanges();
}
}
}
Now I have business wich will call methods from the factories:
public void Business()
{
try
{
OneDaoFactory.AddTreatment(dto);
SecondDaoFactory.Add(dto2);
throw new Exception("make a rollback");
}
catch(Exception ex)
{
//rollback
}
}
Is there any way to create a transaction in the business that will manage all the contexts created by the factories ? Other than create a Context in the business and pass it over to all the DaoFactories ?
I found things about TransactionScope
, but from what I saw, it is for SqlServer. I tried to manually open a connection and a transaction but the contexts seems to reopen theirs owns, so my rollback did nothing.
EDIT
If possible, I would like to not include reference to EF in the business. Like using another Factory to open and close the transaction
Upvotes: 3
Views: 5234
Reputation: 7848
You can do this by opening your own connection EntityConnection
, then open a transaction and pass the connection to the object contexts:
public class OneDaoFactory
{
private EntityConnection conn; // initialize from outside
//...
public int AddTreatment(Dto dto)
{
using (Context bdd = new Context(conn))
{
//Make some changes in database
bdd.SaveChanges();
}
}
}
public void Business()
{
EntityConnection conn = new EntityConnection(ConnectionString);
OneDaoFactory.SetConnection( conn );
SecondDaoFactory.SetConnection( conn );
using( var ts = new TransactionScope())
{
OneDaoFactory.AddTreatment(dto);
SecondDaoFactory.Add(dto2);
throw new Exception("make a rollback);
ts.Complete();
}
}
Hope this helps.
Upvotes: 3