Rollback SqlServer on writing two different tables

1

Premise:

I'm using EntityFramework6 for data persistence in SQLServer. At some point I need to write data in two different tables, but the second table has dependency on the first example.

try{

    MetodoPersisteNaTabelaA();

    MetodoPersisteNaTabelaB();

}
exception(Exception e){
    Erro();
}

I need if there is error writing table B that rolls back to table A.

    
asked by anonymous 08.02.2018 / 12:36

1 answer

3

Good morning, in case you should be instantiating the connection at some point, either inside the method or in the construction of the class, in this connection, I suggest you use the transaction feature of the EF itself and after using the methods execute the committee of the context object or the rollback in case of error.

using (var context = new BloggingContext()) 
{ 
    using (var dbContextTransaction = context.Database.BeginTransaction()) 
    { 
        try 
        { 
            MetodoPersisteNaTabelaA();
            MetodoPersisteNaTabelaB();
            context.SaveChanges();
            dbContextTransaction.Commit(); 
        }
        catch (Exception) 
        { 
            dbContextTransaction.Rollback(); 
        } 
    }
}

Follow msdn's link with more explanations of the subject: link

    
15.02.2018 / 12:07