Transactions in Entity Framework
1. Using DbContextTransaction
Entity Framework allows you to manage transactions using the BeginTransaction
method of the DbContext
.
Example:
using (var context = new YourDbContext()) { using (var transaction = context.Database.BeginTransaction()) { try { // Perform multiple operations var newEntity = new YourEntity { Name = "Example" }; context.YourEntities.Add(newEntity); context.SaveChanges(); var anotherEntity = new AnotherEntity { Value = "Test" }; context.AnotherEntities.Add(anotherEntity); context.SaveChanges(); // Commit transaction transaction.Commit(); } catch (Exception ex) { // Rollback transaction if there is any error transaction.Rollback(); Console.WriteLine(ex.Message); } } }
2. Using TransactionScope
You can use the TransactionScope
class for more advanced scenarios, which allows transactions across multiple DbContext
instances.
Example:
using System.Transactions; using (var scope = new TransactionScope()) { try { using (var context1 = new YourDbContext()) { // Perform operations on first DbContext var entity1 = new YourEntity { Name = "Entity1" }; context1.YourEntities.Add(entity1); context1.SaveChanges(); } using (var context2 = new AnotherDbContext()) { // Perform operations on second DbContext var entity2 = new AnotherEntity { Value = "Entity2" }; context2.AnotherEntities.Add(entity2); context2.SaveChanges(); } // Commit the transaction scope.Complete(); } catch (Exception ex) { // Transaction will be rolled back automatically if not completed Console.WriteLine(ex.Message); } }
3. Using EF Core with IDbContextTransaction
In Entity Framework Core, transactions are handled using the IDbContextTransaction
interface.
Example:
using (var context = new YourDbContext()) { using (var transaction = await context.Database.BeginTransactionAsync()) { try { // Perform database operations context.YourEntities.Add(new YourEntity { Name = "Entity1" }); await context.SaveChangesAsync(); context.AnotherEntities.Add(new AnotherEntity { Value = "Entity2" }); await context.SaveChangesAsync(); // Commit transaction await transaction.CommitAsync(); } catch (Exception ex) { // Rollback transaction await transaction.RollbackAsync(); Console.WriteLine(ex.Message); } } }