title: How to avoid not-safe context operations in EF Core?
body: <p>I'd want to know how why creating instances of other classes with current database context instances as a parameter and using that db context causes this exception to be raised</p>
  
  <blockquote>
    <p>'A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.'</p>
  </blockquote>
  
  <p>Imma use this sample code to show the problem</p>
  
  <pre><code>public class TestController : Controller
  {
      private readonly DbContext dbContext;
  
      public Controller(DbContext ctx)
      {
          dbContext = ctx;
      }
  
      public async Task&lt;IActionResult&gt; Test(string id)
      {
          var isValid = new otherClass(dbContext).Validate(id);
  
          if (!isValid)
          {
              return View("error");
          }
  
          var user = dbContext.Users.FirstOrDefault(x =&gt; x.Id == id);
  
          user.Age++;
  
          dbContext.SaveChanges(); // exception is being raised here. It is second .SaveChanges() here  
  
          return View();
      }
  }
  </code></pre>
  
  <hr>
  
  <pre><code>public class otherClass
  {
      private readonly DbContext dbContext;
  
      public otherClass(DbContext ctx)
      {
          dbContext = ctx;
      }
  
      public bool Validate(string id)
      {
          var user = dbContext.Users.FirstOrDefault(x =&gt; x.Id == id);
  
          user.ValidationAttempt = DateTime.Now;
  
          dbContext.SaveChanges();
  
          return user.HasConfirmedEmail;
      }
  }
  </code></pre>