title: Entity Framework Object Context Refresh
body: <p>I have a LINQ Query that returns a single object - the context is an ObjectContext not a DbContext</p>
  
  <pre><code>var q = from c in context.x //this has various includes but this just an example
  where c.Id == xId
  select c;
  
  X x = q.FirstOrDefault();
  </code></pre>
  
  <p>I am then attaching a collection to this by using the following </p>
  
  <pre><code>ObjectQuery&lt;Z&gt; y = x.Y.CreateSourceQuery().Include("1").Include("2");
  x.Y.Attach(y);
  </code></pre>
  
  <p>However there is a problem where I attempt to refresh the loaded object and if any items attached in the source query were removed they do not change on refresh.I believe this is because the context only loads each object once and keeps it cached, however I need to keep the context open as I need to save back to the database.</p>
  
  <p>I have attempted to refresh using the following:</p>
  
  <pre><code>context.Refresh(RefreshMode.StoreWins, y);
  </code></pre>
  
  <p>or triggering a triggering a refresh by setting the entity state to modified:</p>
  
  <pre><code>context.ObjectStateManager.ChangeObjectState(pb, EntityState.Modified);
  </code></pre>
  
  <p>I understand that with a DB context you can refresh the entity forcing a database refresh, my question would be is it possible to force the refresh using ObjectContext.</p>
  
  <p>Using DbContext we were able to get the desired results by refreshing everything however as you can imagine this was very slow.</p>
  
  <pre><code>var refreshableObjects = context.ChangeTracker.Entries().Select(e =&gt; e.Entity).ToList();
  foreach (var obj in refreshableObjects)
  {
      ((IObjectContextAdapter)context).ObjectContext.ObjectStateManager.GetRelationshipManager(obj).GetAllRelatedEnds().Where(r =&gt; r.IsLoaded).ToList().ForEach(c =&gt; c.Load());
  }
  </code></pre>