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=
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;
ctx.SaveChanges();
oTran.Rollback();
}
}
}
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.
Tags - SQL Entity Framework
Last Modified : June 2023