title: Service pattern entity framework asp.net mvc
body: <p>I want to do unit testing in my asp.net mvc entity framework 6 project and it forced me to look at my code. I had my controllers exposed to my context and decided I should probably separate it out. I was initially looking at the repository/UoW pattern but after reading a lot I decided on the simple service pattern with DI (i.e., the controller is injected with a service that has <code>GetProducts()</code>, <code>FindProduct()</code>, etc.). </p>
  
  <p>My question is related to the change tracking in this pattern. Before I would just call <code>SaveChanges()</code> after a lot of things were done in a controller method, but separating everything made methods like these:</p>
  
  <pre><code> public void AddRequest(Request request)
      {
          using (PricedNotesContext ctxt = new PricedNotesContext())
          {
              ctxt.Requests.Add(request);
              ctxt.SaveChanges();
          }
      }
  
   public void DeleteRequestData(BaseRequestData reqData)
      {
          using (PricedNotesContext ctxt = new PricedNotesContext())
          {
              ctxt.RequestData.Remove(reqData);
              ctxt.SaveChanges();
  
          }
      }
  </code></pre>
  
  <p>In the above you see that <code>SaveChanges()</code> is called twice. But I only want it called once. I only want my changes to persist if both operations completed successfully. Is the recommended solution to just have a method called <code>SaveChanges()</code> and <code>Dispose()</code> which obviously calls <code>SaveChanges()</code> and <code>Dispose()</code> exposed to the controller to manage the transaction?</p>
  
  <p>Thanks for your help!</p>