title: Long living Entity Framework context - best practice to avoid data integrity issues
body: <p>As a very rudimentary scenario, let's take these two operations:</p>
  
  <pre><code>UserManager.UpdateFirstName(int userId, string firstName)
  {
      User user = userRepository.GetById(userId);
      user.FirstName = firstName;
      userRepository.SaveChanges();
  }
  
  InventoryManager.InsertOrder(Order newOrder)
  {
      orderRepository.Add(newOrder);
      orderRepository.SaveChanges();
  }
  </code></pre>
  
  <p>I have only used EF in web projects and relied heavily on the stateless nature of the web.  With every request I would get a fresh copy of the context injected into my business layer facade objects (services, managers, whatever you want to call them), all of the business managers sharing the same instance of the EF context.  Currently I am working on a WPF project and I'm injecting the business managers and subsequently the repositories that they use directly into the View Model.</p>
  
  <p>Let's assume a user is on a complicated screen and his first button click calls the UpdateFirstName() method.  Let's assume SaveChanges() fails for whatever reason.  Their second button click will invoke the InsertOrder() method.</p>
  
  <p>On the web this is not an issue as the context for operation #2 is not related (new http request) to the context used by operation #1.  On the desktop however, it's the same context across both actions.  The issue arises in the fact that the user's first name has been modified and as such is tracked by the context.  Even though the original SaveChanges() didn't take (say the db was not available at that time), the second operation calling SaveChanges() will not only insert the new order, it will also update the users first name.  In just about every cause this is not desirable, as the user has long forgotten about their first action which failed anyway.</p>
  
  <p>This is obviously being a silly example, but I always tend to bump into these sort of scenarios where I wish I could just start fresh with a new context for every user action as opposed having a longer lived (for the life of the WPF window for example) context.</p>
  
  <p>How do you guys handle these situations?</p>