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.
- public string SaveCustomer(Customer customer) {
- string result = "";
- // Start the Begin Transaction
- using(var dbContextTransaction = context.Database.BeginTransaction()) {
- try {
- //Write your logic- Insert /Update / Delete for single or multiple tables
- OperationDataContext OdContext = new OperationDataContext();
- tblCustomers objCustomer = new tblCustomers ();
- objCustomer.course_name = "Name";
- objCustomer.Desc = "Desc";
- objCustomer.modified_date = DateTime.Now;
- OdContext.tblCustomers.Add(objCustomer);
- OdContext.SaveChanges();
- //Adds an entity in a pending insert state to this System.Data.Linq.Table<TEntity>and parameter is the entity which to be added
- result = "Success";
- // Once your Single/Multiple table insert /Update/Delete operation done all operation should commit to database
- dbContextTransaction.Commit();
- } catch (Exception e) {
- result = e.Message;
- // If any operation getting error on the insert /Update/Delete operation all operation rollback. It should not commit to database
- dbContextTransaction.Rollback();
- }
- }
- return result;
- }

Join the conversation! Your thoughts help the community grow.