I have a created an Entity Framework 6 transaction and I update some data inside of it, then an exception is being thrown by some code. I catch the exception and rollback the transaction. However, when I check the database I see that the data has been updated even though I rolled back the transaction.
How can I prevent data from being saved when an exception happens?
public void MainMethod(){
try {
MethodA();
}
catch (Exception) {
using (var tran = _context.Database.BeginTransaction())
{
try
{
var logObject = new LogObject();
logObject.text = "some text";
_context.LogObjects.Add(logObject);
_context.SaveChanges();
tran.Commit();//when an exception happens in MethodA, the method a data still saves, when this transaction gets committed here.
}
catch (Exception)
{
tran.Rollback();
throw;
}
}
}
}
public void MethodA()
{
using (var tran = _context.Database.BeginTransaction())
{
try
{
UpdateMyData();
_context.SaveChanges();
tran.Commit();
tran.Dispose();
}
catch (Exception)
{
tran.Rollback();
tran.Dispose();
throw;
}
}
}
public void UpdateMyData()
{
try
{
var dataRecord = _context.MySampleDataRecords.Where(x => x.isActive).First();
dataRecord.isActive = false; //This update is being saved to the database and it should not be saved
}
catch (Exception ex)
{
throw new Exception("Test exception");
}
}