0

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?

rcs
  • 6,713
  • 12
  • 53
  • 75
  • 1
    Stop using the repository pattern over EF, secondly, stop reusing dbContexts – TheGeneral Nov 20 '19 at 08:14
  • You fix this by changing your design entirely. A DbContext uses a design pattern called "unit of work". Wrapping it in, and sharing it between, repository classes is asking for trouble. – CodeCaster Nov 20 '19 at 08:14
  • Does this answer your question? [Undo changes in entity framework entities](https://stackoverflow.com/questions/5466677/undo-changes-in-entity-framework-entities) – Eldar Nov 20 '19 at 08:36
  • @CodeCaster so how should I change my design? – rcs Nov 20 '19 at 08:43

0 Answers0