title: EntityFramework context returning old data
body: <p>I'm working on an ASP.NET web forms project that has an implementation of a user repository that is acting strangely. I'm experiencing the following behavior:</p>
  
  <ol>
  <li>User logs in with a valid username/password. They get in successfully.</li>
  <li>User logs out.</li>
  <li>I change the password in the database (for argument's sake).</li>
  <li>User logs in again using the new password. However, the login is rejected as invalid.</li>
  </ol>
  
  <p>If I set a breakpoint at the "user" variable in the ValidateUser() method and inspect the password, it has the OLD password even though the database clearly has the new password saved. It seems to me like there's some problem with the architecture of the repository that is causing it to load an old context or something along those lines, but it creates a new PortalContext() each time the class is instantiated. Any ideas?</p>
  
  <pre><code>public class BaseRepository
  {
      protected readonly PortalContext Context = new PortalContext();
  }
  
  public class UserRepository : BaseRepository, IUserRepository
  {
      public bool ValidateUser(string username, string password)
      {
         var user = Context.Users.FirstOrDefault(x =&gt; x.LoginName == username);
  
         if (user == null) return false;
         return user.Password == password;
      }
  }
  </code></pre>
  
  <p>.NET CODE BEHIND</p>
  
  <pre><code>public partial class _default
  {
      private readonly IUserRepository _userRepository = new UserRepository();
  
      protected void btnSubmit_Click(object sender, EventArgs e)
      {
          if (_userRepository.ValidateUser(txtUsername.Text, txtPassword.Text)
          {
              // Log user in
          }
      }
  }
  </code></pre>
  
  <p><strong>EDIT:</strong> If I update ValidateUser() to the following code, the problem goes away. This seems to confirm that it has something to do with it hanging on to the old context. </p>
  
  <pre><code>public bool ValidateUser(string username, string password)
  {
      using (var context = new PortalContext())
      {
          var user = context.Users.FirstOrDefault(x =&gt; x.LoginName == username);
  
          if (user == null) return false;
          return user.Password == password;
      }
  }
  </code></pre>