using (var transaction = context.Database.BeginTransaction()) { try { // Perform database actions here context.SaveChanges(); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); } }
// Create a transaction using (var transaction = _context.Database.BeginTransaction()) { try { // Create, update or delete one or more entities _context.Customers.Add(new Customer { Name = "John Doe" }); _context.SaveChanges(); // Commit the transaction transaction.Commit(); } catch (Exception ex) { // Rollback the transaction if an exception occurs transaction.Rollback(); } }This example shows how to create, update or delete one or more entities in the database and then commit the transaction. If an exception occurs during the transaction, it will be rolled back to undo any changes made. The package library for this method is Microsoft.EntityFrameworkCore.