How to use Database Transactions with .NET CodeFirst Entity Framework

Transactions are fundamental to database operations where a sequence of steps must all pass or fail. If an error occurs with one part, you are going to need to roll everything. CodeFirst Entity Framework has functionality for providing for transactions.

Hopefully you have been following my CodeFirst articles so you should have an application and a database ready to go so we don't need to cover old ground. If you haven't I suggest going to the first article and following from there. The first article is How to Create a CodeFirst Entity Framework Project using Visual Studio.

Creating a transaction is simple, just create a transaction object from the DbContext object and carry on as usual. The following code example should be able to help you understand what I'm talking about.

    static void Main(string[] args)
        string sConn = "Data Source=;Initial Catalog=Shop;Integrated Security=True";

        using (var ctx = new Shop(sConn))
             using (var oTran = ctx.Database.BeginTransaction())
                Customer oCust = new Customer();
                oCust.CustomerID =6;
                ctx.Entry(oCust).State = System.Data.Entity.EntityState.Deleted;

So you can see from the above example, we are creating a Transaction object using the ctx.Database object and then rolling back later. You'll see it works by attempting to delete a record from your Customer table and then rolling back. When you check the database, your record should still be there.

If you change the Rollback to Commit and run, you will find that the record no longer exists in the database if you using SQL Management Studio to do a select statement on the table.

Other Articles of Interest

Next Article : How to disable and enable a table trigger in SQL Server
Previous Article : How to delete a record using .NET CodeFirst Entity Framework

Tags - SQL Entity Framework

Last Modified : 14th May 2023
Date Published : 14th August 2022

Comments and Questions

There's no register feature and no need to give an email address if you don't want to. All messages will be reviewed before being displayed. Comments may be merged or altered slightly, such as if it contains an email or website address.

You can decline to give a name; if that is the case, the comment will be attributed to a random star. A name is preferred, even if it's a random made-up one by yourself.

If you give an email address, you may receive an email notifying you when someone else has added a comment to the same page. In the email will be a link to unsubscribe to further notifications.


About... / Contact.. / Cookie...