title: Invalidating/Disabling Entity Framework cache
body: <p>I see there are plenties of question on EF cache, but I have found no solution yet to my problem.</p>
  
  <h2>The straight question is</h2>
  
  <p>How do I completely disable Entity Framework 6 cache? Or, can I programmatically tell EF to forget about the cache because something happened to data?</p>
  
  <h3>Background</h3>
  
  <p>First, I have <strong>inherited</strong> an application made of a strange mixture of EF (model-first to define entities) and plain old SQL (to manipulate data). What I did was to refactor the application in order to:</p>
  
  <ul>
  <li>Make simple queries (like <code>GetAll()</code> for an entity) use EF6 LINQ</li>
  <li>Leave complex data manipulation in SQL, using <code>DbContext.Database.Connection</code> when needed</li>
  <li>Add <code>Spring.Web</code> support to enable DI and transactions (not yet)</li>
  </ul>
  
  <p>At the current point, I have reorganized the code so that the main function of the application (running complex SQL queries on huge datasets) works as it did before, but then lookup domain entity manipulation is done smarter using <em>as most</em> Entity Framework as possible</p>
  
  <h3>As most....</h3>
  
  <p>One of the pages I inherited is a multi-checkbox page I'm going to show you for best understanding. I won't discuss the previous implementor's choice, because it's cheaper to fix my current problem and later refactor code than blocking development for a broken feature.</p>
  
  <p>This is how the page looks like</p>
  
  <p><img src="https://i.stack.imgur.com/1Fbxh.jpg" alt="enter image description here"></p>
  
  <p>Basically the <code>Controller</code> method is the following</p>
  
  <pre><code>    [HttpPost]
      public ActionResult Index(string[] codice, string[] flagpf, string[] flagpg, string[] flagammbce, string[] flagammdiv, string[] flagammest,
          string[] flagintab, string[] flagfinanz, string[] flagita, string[] flagest, string pNew){
              Sottogruppo2015Manager.ActivateFlagFor("pf", flagpf);
              Sottogruppo2015Manager.ActivateFlagFor("pg", flagpg);
              Sottogruppo2015Manager.ActivateFlagFor("ammbce", flagammbce);
              Sottogruppo2015Manager.ActivateFlagFor("ammdiv", flagammdiv);
              Sottogruppo2015Manager.ActivateFlagFor("ammest", flagammest);
              Sottogruppo2015Manager.ActivateFlagFor("intab", flagintab);
              Sottogruppo2015Manager.ActivateFlagFor("finanz", flagfinanz);
              Sottogruppo2015Manager.ActivateFlagFor("ita", flagita);
              Sottogruppo2015Manager.ActivateFlagFor("est", flagest);
  
              return RedirectToAction("Index", new { pNew });
   }
  </code></pre>
  
  <p>Each <code>string[]</code> parameter is a column in the table. The <code>ActivateFlagFor</code> method runs two queries in sequence</p>
  
  <pre><code>UPDATE table SET --param1-- = 0;
  UPDATE table SET --param1-- = 1 where id in (--param2--)
  </code></pre>
  
  <h3>When the cache kicks in</h3>
  
  <p>The following is the behaviour:</p>
  
  <ul>
  <li>I first load the page issuing a LINQ select: checks match the ones and zeroes in columns</li>
  <li>I change one or more checks and submit</li>
  <li>The controller issues the queries to update checks in the DB</li>
  <li>Before <strong>redirecting</strong> (!means new request!) to reload the page, I check the DB and the changes are applied</li>
  <li>The page reloads issuing the same LINQ select above: <strong>old checks are displayed</strong></li>
  </ul>
  
  <p>I am sure that this is a caching problem, because reloading the application fixes the problem.
  Since the main feature of the application is totally SQL based, changes to lookup tables are reflected into main operation and that's the correct behaviour.</p>
  
  <p>I understand that EF caching is a great feature for performance, but in my case I just don't want it, at least until I migrate the whole application to LINQ DML (probably impossible).</p>
  
  <h3>How I use the <code>DbContext</code></h3>
  
  <p>Of course some of you may ask "how do you use your DbContext?" "do you dispose of it correctly?".</p>
  
  <ul>
  <li>I haven't yet integrated Spring transactions in my Manager classes</li>
  <li>Each object that performs <em>actions</em> on the database is a <code>I&lt;Entity&gt;Manager</code> extending <code>BaseManager</code></li>
  <li><code>DbContext</code> is a request-scoped Spring object. I already <a href="https://stackoverflow.com/questions/28232703/disposable-request-scoped-object">asked about disposing request-scoped objects</a> but I currently implemented a workaround that, while bad, <strong>correctly disposes of</strong> the DbContext at the end of the request.</li>
  </ul>
  
  <h3>Example code</h3>
  
  <pre><code>public class ExampleManagerImpl : BaseManager, IExampleManager
  {
      public void ActivateFlagFor(string aFlag, string[] aList)
      {
          string sql = "UPDATE table SET flag" + aFlag + " = 0";
          RunStatementV1(sql);
  
          if (aList != null &amp;&amp; aList.Any())
          {
              sql = "UPDATE table SET flag" + aFlag + " = 1 WHERE id in (" + aList.ToCsvApex() + ")";
              RunStatementV1(sql);
          }
      }
  
      public IList&lt;Models.Example&gt; GetAll()
      {
          return DataContext.example.ToList(); //I don't dispose of the DataContext willingly
      }
  }
  </code></pre>
  
  <p>and</p>
  
  <pre><code>public abstract class BaseManager {
  
      public DbContext DataContext { get; set; } //Autowired
  
      protected void RunStatementV1(string aSqlStatement)
      {
          IDbConnection connection = DataContext.Database.Connection;
          if (connection.State == ConnectionState.Closed || connection.State == ConnectionState.Broken) connection.Open(); //Needed because sometimes I found the connection closed, even if I don't dispose of it
          using (IDbCommand command = connection.CreateCommand())
          {
              command.CommandText = aSqlStatement;
              command.ExecuteNonQuery();
          }
  
      }
  }
  </code></pre>
  
  <h3>What I tried</h3>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/4346494/how-to-stop-entity-framework-caching">How to stop entity framework caching</a> : disabling lazy loading didn't work</li>
  <li><a href="https://stackoverflow.com/a/22818783/471213">https://stackoverflow.com/a/22818783/471213</a>: <code>Detach</code> seems to solve the problem but I'd need to apply it to dozen of entities, in order to revert someday in the future</li>
  </ul>