How to manually manage transactions?
(BeginTransaction, Commit,
Rollback)
- Use DbContext.Database.BeginTransaction() to start a transaction.
- Call Commit() to save changes or Rollback() to undo.
- Useful for combining multiple operations that should succeed or fail as a unit.
using var transaction = context.Database.BeginTransaction();
try {
// Perform multiple operations
context.SaveChanges();
transaction.Commit();
} catch {
transaction.Rollback();
throw;