title: Using DbContext SaveChanges with Transactions
body: <p>As MSDN <a href="http://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext(v=vs.103).aspx" rel="noreferrer">confirms</a>, in EF 5 and on, the DbContext class is "a combination of the Unit-Of-Work and Repository patterns."  In the web applications I build, I tend to implement the Repository and Unit-Of-Work patterns on top of the existing DbContext class.  Lately, like many others out there, I've found that this is overkill in my scenario.  I am not worried about the underlying storage mechanism ever changing from SQL Server, and while I appreciate the benefits that unit testing would bring, I still have a lot to learn about it before actually implementing it in a live application.</p>
  
  <p>Thus, my solution is to use the DbContext class directly as the Repository and Unit-Of-Work, and then use StructureMap to inject one instance per request to individual service classes, allowing them to do work on the context.  Then in my controllers, I inject each service I need and call the methods necessary by each action accordingly.  Also, each request is wrapped in a  transaction created off of the DbContext at the beginning of the request and either rolled back if any type of exception occurred (whether it be an EF error or application error) or committed if all is well.  A sample code scenario is below.  </p>
  
  <p><em>This sample uses the Territory and Shipper tables from the Northwind sample database.  In this sample admin controller, a territory and a shipper are being added at the same time.</em></p>
  
  <p><strong>Controller</strong></p>
  
  <pre><code>public class AdminController : Controller 
  {
      private readonly TerritoryService _territoryService;
      private readonly ShipperService _shipperService;
  
      public AdminController(TerritoryService territoryService, ShipperService shipperService)
      {
          _territoryService = territoryService;
          _shipperService = shipperService;
      }
  
      // all other actions omitted...
  
      [HttpPost]
      public ActionResult Insert(AdminInsertViewModel viewModel)
      {
          if (!ModelState.IsValid)
              return View(viewModel);
  
          var newTerritory = // omitted code to map from viewModel
          var newShipper = // omitted code to map from viewModel
  
          _territoryService.Insert(newTerritory);
          _shipperService.Insert(newShipper);
  
          return RedirectToAction("SomeAction");
      }
  }
  </code></pre>
  
  <p><strong>Territory Service</strong></p>
  
  <pre><code>public class TerritoryService
  {
      private readonly NorthwindDbContext _dbContext;
  
      public TerritoryService(NorthwindDbContext dbContext) 
      {
          _dbContext = dbContext;
      }
  
      public void Insert(Territory territory)
      {
          _dbContext.Territories.Add(territory);
      }
  }
  </code></pre>
  
  <p><strong>Shipper Service</strong></p>
  
  <pre><code>public class ShipperService
  {
      private readonly NorthwindDbContext _dbContext;
  
      public ShipperService(NorthwindDbContext dbContext) 
      {
          _dbContext = dbContext;
      }
  
      public void Insert(Shipper shipper)
      {
          _dbContext.Shippers.Add(shipper);
      }
  }
  </code></pre>
  
  <p><strong>Creation of Transaction on Application_BeginRequest()</strong></p>
  
  <pre><code>// _dbContext is an injected instance per request just like in services
  HttpContext.Items["_Transaction"] = _dbContext.Database.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
  </code></pre>
  
  <p><strong>Rollback or Commit of Transaction on Application_EndRequest</strong></p>
  
  <pre><code>var transaction = (DbContextTransaction)HttpContext.Items["_Transaction"];
  
  if (HttpContext.Items["_Error"] != null) // populated on Application_Error() in global
  {
      transaction.Rollback();
  }
  else
  {
      transaction.Commit();
  }
  </code></pre>
  
  <p>Now this all seems to work well, but the only question I have now is where is it best to call the <code>SaveChanges()</code> function on the DbContext?  Should I call it in each Service layer method?</p>
  
  <pre><code>public class TerritoryService
  {
      // omitted code minus changes to Insert() method below
  
      public void Insert(Territory territory)
      {
          _dbContext.Territories.Add(territory);
          _dbContext.SaveChanges();  // &lt;== Call it here?
      }
  }
  
  public class ShipperService
  {
      // omitted code minus changes to Insert() method below
  
      public void Insert(Shipper shipper)
      {
          _dbContext.Shippers.Add(shipper);
          _dbContext.SaveChanges();  // &lt;== Call it here?
      }
  }
  </code></pre>
  
  <p>Or should I leave the service class Insert() methods as is and just call SaveChanges() right before the transaction is committed?</p>
  
  <pre><code>var transaction = (DbContextTransaction)HttpContext.Items["_Transaction"];
  
  // HttpContext.Items["_Error"] populated on Application_Error() in global
  if (HttpContext.Items["_Error"] != null) 
  {
      transaction.Rollback();
  }
  else
  {
      // _dbContext is an injected instance per request just like in services
      _dbContext.SaveChanges(); // &lt;== Call it here?
      transaction.Commit();
  }
  </code></pre>
  
  <p>Is either way okay?  Is it safe to call SaveChanges() more than once since it is wrapped in a transaction?  Are there any issues I may run into by doing so?  Or is it best to call SaveChanges() just once right before the transaction is actually committed?  I personally would rather just call it at the end right before the transaction is committed, but I want to be sure I am not missing any gotcha's with transactions or doing something wrong?  If you read this far, thanks for taking the time to help.  I know this was a long question.</p>