LINQ Transaction, Commit And Roll Back

There is a very good feature to achieve roll back in LINQ using TransactionScope.
A transaction is a unit of work,
  • If a transaction is successful, all of the data operations are committed and saved to it.
  • If a transaction encounters errors/exceptions and must be canceled or rolled back, then all of the data modifications/operations need to be removed. 
For example, you have two tables named Customer and CustomerDetails.

As I've declared two tables, let's create a scenario. Suppose you have updated some value in the current context using db.SubmitChanges() for the customer table, while on the other hand, if an exception occurs for CustomerDetails table it would be weird.
Our main target is to achieve roll-back transactions if something goes wrong, rather than saving uncompleted code. 
Please see the below code for commit and Rollback in C# LINQ.
  1. public string SaveCustomer(Customer customer) {      
  2.     string result = "";      
  3.     // Start the Begin Transaction             
  4.     using(var dbContextTransaction = context.Database.BeginTransaction()) {      
  5.         try {      
  6.             //Write your logic- Insert /Update / Delete for single or multiple tables             
  7.                    OperationDataContext OdContext = new OperationDataContext();    
  8.                     tblCustomers objCustomer = new tblCustomers ();    
  9.                      objCustomer.course_name = "Name";    
  10.                      objCustomer.Desc = "Desc";    
  11.                      objCustomer.modified_date = DateTime.Now;    
  12.                      OdContext.tblCustomers.Add(objCustomer);
  13.                      OdContext.SaveChanges();
  14.     //Adds an entity in a pending insert state to this System.Data.Linq.Table<TEntity>and parameter is the entity which to be added
  15.             result = "Success";      
  16.             // Once your Single/Multiple table insert /Update/Delete operation done all operation should commit to database             
  17.             dbContextTransaction.Commit();      
  18.         } catch (Exception e) {      
  19.             result = e.Message;      
  20.             // If any operation getting error on the insert /Update/Delete operation all operation rollback. It should not commit to database            
  21.             dbContextTransaction.Rollback();      
  22.         }      
  23.     }      
  24.     return result;      
  25. }      

Next Recommended Reading Reversing a Dictionary in LINQ and C#