Mark13426
Mark13426

Reputation: 2639

Working with Entity Framework 6 Transactions

I have a set of questions regarding the use of transactions in EF 6. I use the following code template for my database queries:

using (var ctx = new MyContext(connectionString))
{
    using (var tx = ctx.Database.BeginTransaction(IsolationLevel.Snapshot))
    {
          try
          {
               // query database
               ctx.SaveChanges();
               tx.Commit();
          }
          catch(Exception ex)
          {
               tx.Rollback();

               if(ex is A) // handle A
               if(ex is B) // handle B                   

               throw;
          }
    } 
}

Upvotes: 0

Views: 1703

Answers (1)

Pratik Bhoir
Pratik Bhoir

Reputation: 2144

You dont have to actually use transactions in Entity Framework.

The default isolation mode is read committed and fits perfectly to 99% of your needs, eg. reading data. When you want to save the changes you made to the database (Create, Update, Delete), EntityFramework is smart enough to create a transaction without your notice behind the scenes to wrap the changes. You can be sure that everything will be saved or every change will be discarded (Atomicity).

Look Here https://coderwall.com/p/jnniww

  • When you make the call to SaveChanges, I believe the Entity Framework will perform all those operations in a single transaction. And when excpetion occurs, it rollbacks automatically. So, you dont have to call rollback. or use transaction.
  • Entity Framework has handled transactions internally, you can use it when you have to do operations on multiple databases
  • I am unaware about this SqlAzureExecutionStrategy for connection resiliency. But, this feature is complemented by the new ADO.Net idle connection resiliency in .NET Framework 4.5.1 http://blogs.msdn.com/b/dotnet/archive/2013/10/17/net-framework-4-5-1-rtm-gt-start-coding.aspx

The Basic Entity Framework Operations Block..

using (var context = new ProductContext()) 
{ 
    try
    {
        // Perform data access using the context 
        context.SaveChanges();
    }
    catch(Exception ex)
    {
        //handle exception
    }

}

Hope it may Help you, Have a nice day.

Upvotes: 1

Related Questions