Rollback Sqlserver recording two separate tables

Asked

Viewed 55 times

1

Premise:

I’m using Entityframework6 for data persistence in Sqlserver. In a certain period I need to record data on two different tables, but the second table is dependent on the first example.

try{

    MetodoPersisteNaTabelaA();

    MetodoPersisteNaTabelaB();

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

I need that if there is an error in the recording of table B that gives rollback in table A.

1 answer

3


Good morning, in case you must be instantiating the connection at some point, either within the method or in the construction of the class, in this connection, I suggest that you use the transaction feature of the EF itself and after using the methods run the Comit 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 link with more explanation of the subject: https://msdn.microsoft.com/en-us/library/dn456843(v=vs.113). aspx

Browser other questions tagged

You are not signed in. Login or sign up in order to post.