title: EF 4.3 using local cache instead of re-fetching from database
body: <p>Can someone explain to me why my EF (4.3) code first code below is resulting in the "old" password being retrieved. </p>
  
  <pre><code>using (var context = new CableSenseInstanceConfiguratorContext())
  {
      var user = context.Installers.Where(u =&gt; u.UserName == "admin").FirstOrDefault();
      Console.WriteLine(user.Password); // Outputs "oldpassword"
  
      // Change the details on a different context;
      using (var context2 = new CableSenseInstanceConfiguratorContext())
      {
          var installer = context2.Installers.Single(i =&gt; i.UserName == "admin");
          installer.Password = "changed"; 
          context2.SaveChanges();
      }
  
      var user2 = context.Installers.Where(u =&gt; u.UserName == "admin").FirstOrDefault();
      Console.WriteLine(user2.Password); // Outputs "oldpassword"
  }
  </code></pre>
  
  <p>The password is "oldpassword" to start. So I'm changing the password inside another context (context2), and then fetching it again into user2. I can verify that the output is "oldpassword" for both. From profiling the SQL, I can see that the password does get changed, I can also see that the code that populates user2 <em>IS</em> going to the database, but it's just not using those values. </p>
  
  <p>I understand that EF has the concept of the Local context as a way of caching and tracking entities, but from what I understand, a <code>context.Installers.Where(..)</code> should force a refetch from the database, whereas a <code>context.Installers.Find()</code> should look in the local context. It seems that no matter how I query Installers, it is using the local cache.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Thanks to @Reinard for the solution. I was misunderstanding the docs - I read from <a href="http://blogs.msdn.com/b/adonet/archive/2011/01/28/using-dbcontext-in-ef-feature-ctp5-part-3-finding-entities.aspx" rel="nofollow">here</a>:</p>
  
  <blockquote>
    <p>Note that DbSet and IDbSet always create queries against the database
    and will always involve a round trip to the database even if the
    entities returned already exist in the context.</p>
  </blockquote>
  
  <p>So I assumed that because it would go to the database, it would re-fetch my object. What actually happened is that it went to the database, fetched the object, found I already was tracking that object (because of the previous load), and so I ended up with the old object - this is actually what the docs say!</p>
  
  <p>Using <code>context.Installers.Local.Clear()</code> makes no difference surprisingly, I needed <code>AsNoTracking().</code></p>