title: Global Entity Framework Context in WPF Application
body: <p>I am in the middle of development of a WPF application that is using Entity Framework (.NET 3.5).  It accesses the entities in several places throughout.  I am worried about consistency throughout the application in regard to the entities.  Should I be instancing separate contexts in my different views, or should I (and is a a good way to do this) instance a single context that can be accessed globally?</p>
  
  <p>For instance, my entity model has three sections, Shipments (with child packages and further child contents), Companies/Contacts (with child addresses and telephones), and disk specs.  The Shipments and EditShipment views access the DiskSpecs, and the OptionsView manages the DiskSpecs (Create, Edit, Delete).  If I edit a DiskSpec, I have to have something in the ShipmentsView to retrieve the latest specs if I have separate contexts right?</p>
  
  <p>If it is safe to have one overall context from which the rest of the app retrieves it's objects, then I imagine that is the way to go.  If so, where would that instance be put?  I am using VB.NET, but I can translate from C# pretty good.  Any help would be appreciated.  </p>
  
  <p>I just don't want one of those applications where the user has to hit reload a dozen times in different parts of the app to get the new data.</p>
  
  <p><strong>Update:</strong></p>
  
  <p>OK so I have changed my app as follows:</p>
  
  <ol>
  <li>All contexts are created in Using Blocks to dispose of them after they are no longer needed.</li>
  <li>When loaded, all entities are detatched from context before it is disposed.</li>
  <li>A new property in the MainViewModel (ContextUpdated) raises an event that all of the other ViewModels subscribe to which runs that ViewModels RefreshEntities method.</li>
  <li>After implementing this, I started getting errors saying that an entity can only be referenced by one ChangeTracker at a time.  Since I could not figure out which context was still referencing the entity (shouldn't be any context right?) I cast the object as IEntityWithChangeTracker, and set SetChangeTracker to nothing (Null).</li>
  </ol>
  
  <p>This has let to the current problem:
  When I Null the changeTracker on the Entity, and then attach it to a context, it loses it's changed state and does not get updated to the database.  However if I do not null the change tracker, I can't attach.  I have my own change tracking code, so that is not a problem.  </p>
  
  <p>My new question is, how are you supposed to do this.  A good example Entity query and entity save code snipped would go a long way, cause I am beating my head in trying to get what I once thought was a simple transaction to work. </p>