I have created 2 repositories, and they are using the same DbContext
MyRepo1 myRepo1 = new MyRepo1(_DBContext);
MyRepo2 myRepo2 = new MyRepo2(_DBContext);
try
{
// Put in transaction
using (var transaction = myRepo1.BeginDBTransaction())
{
try
{
// Some operations here on myRepo1
myRepo1.SaveChanges();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
throw new Exception("Error processing data");
}
}
}
catch (Exception ex)
{
sb.Append("Error = " + ex.ToString() + ".");
}
finally
{
myRepo2.LogData(data);
}
The problem is that, let's say there is error on myRepo1 operations (i.e. exception when calling myRepo1), I want to rollback the transaction. At the point of rollback, it seems fine.
But when I call myRepo2.LogData(data)
, it will throw the same error like when I call myRepo1.SaveChanges()
.
It seems that since the context changes done in myRepo1 is not reversed when calling the transaction.Rollback()
. How to fix this?