Blog

.NET Entity Framework Working with Database Transactions

Transactions are vital part of modern databases. A transaction is a sequence of database operations on one or many tables, which are considered as a single (atomic) operation. If any of the operations in a transaction fails, the transaction is considered to have failed to be committed. In this case, the transaction can be rolled back, which will return the whole database to its initail state. Some may describe transactions in a more human friendly manner as "all-or-nothing".

Here is how to use transactions in .NET Entity Framework 6 and above

using (var db = new DbContext())
{
    using (var tr = db.Database.BeginTransaction())
    {
         db.SaveChanges();
         tr.Commit();
    }
    catch (Exception)
    {
        tr.Rollback();
    }
}