Can’t get too far without Transactions support. Guess what? EF Core’s got your Back!!

A transaction symbolizes a unit of work performed within a database management system against a database, and treated in a coherent and reliable way independent of other transactions. A transaction generally represents any change in database.

If the transaction is committed, all of the operations are successfully applied to the database. If the transaction is rolled back, none of the operations are applied to the database.

The default behavior of a transaction is if the database provider supports transactions, all changes in a single call to SaveChanges() are materialized in a transaction. However, if any one of the changes fails, then the transaction is rolled back without any change(s) being materialized to the database. What this means is that SaveChanges() is guaranteed to either completely succeed, or leave the database in its original state in the event of a failure.

Let’s see this in action, but first, let’s see what we have in our database table called Departments before we call our method.


See the code snippet below. Notice SaveChanges() operation is being used twice. However, LINQ query is executed only once.

      private static void TransactionUpdateDelete()
            using (var db = new DepartmentContext())
                using (var trx = db.Database.BeginTransaction())
                    int depId = 15;
                    var depts = db.Departments.Find(depId);
                    depts.location = "New Delhi";

                    //Delete a record
                    db.Database.ExecuteSqlCommand("delete from dbo.Departments where depId = 16");

                    var deptList = db.Departments.ToList();

                    foreach (var item in deptList)
                        Console.WriteLine(item.depName, item.depName, item.location);

Snapshot of Data View After the Commit(). Notice DepartmentID 15 is updated from New York to New Delhi and DepartmentID 16 is yanked out as a result of the Deletion


And lastly, the output window to demonstrate the successful execution of the two operations, namely, Update and Delete within the context of a Transaction in EF Core.


About Obi Oberoi

Obi Oberoi is a Microsoft MVP (Visual Studio & Development Technologies), developer and a life-long student of continuous learning. Obi enjoys to code, read, and hang out with techies and geeks!
This entry was posted in ORM. Bookmark the permalink.