mehdime / DbContextScope

A simple and flexible way to manage your Entity Framework DbContext instances
http://mehdi.me/ambient-dbcontext-in-ef6/
MIT License
634 stars 271 forks source link

How do I use this with transaction? #46

Closed rosdi closed 8 years ago

rosdi commented 8 years ago

I am trying to figure out what is the correct way to start a transaction and prepare for rollback in case of error...

I notice there is DbContextScopeFactory.CreateWithTransaction(IsolationLevel) in the code but couldn't figure it out how to actually use it.

Is this the proper way to do it?

using (var dbContextScope = DbContextScopeFactory.CreateWithTransaction(IsolationLevel.ReadCommitted))
{
  var dbContext = dbContextScope.DbContexts.Get<MyDbContext>();
  using (var trans = dbContext.Database.BeginTransaction())
  {
      try
      {
          ... do some work here.. modify several tables etc..

         dbContext.SaveChanges();
         trans.Commit();
      }
      catch (Exception)
      {
         trans.Rollback();  //rolback everything
         throw;
      }
  }
}
rosdi commented 8 years ago

Hi nevermind... I found this discussion #12 that pretty much explains it... (apparently I asked the question too soon)...

Cheers.