title: Prevent cached objects to end up in the database with Entity Framework
body: <p>We have an ASP.NET project with Entity Framework and SQL Azure.</p>
  
  <p>A big part of our data only needs to be updated a few times a day, other data is very volatile. </p>
  
  <ul>
  <li>The data that barely changes we cache in memory at startup, detach from the context and than use it mainly for reading, drastically lowering the amount of database requests we have to do.</li>
  <li>The volatile data is requested everytime by a DbContext per Http request.</li>
  <li>When we do an update to the cached data, we send a message to all instances to catch a fresh version of all the data from the SQL server.</li>
  </ul>
  
  <p>So far, so good. </p>
  
  <p>Until we introduced a bug that linked one of these 'cached' objects to the 'volatile' data, and did a SaveChanges.</p>
  
  <p>Well, that was quite a mess.</p>
  
  <p>The whole data tree was added <strong>again</strong> and <strong>again</strong> by every update, corrupting the whole database with a whole lot of duplicated data.</p>
  
  <p>As a complete hack I added a completely arbitrary column with a UniqueConstraint and some gibberish data on one of the root tables; hopefully failing the SaveChanges() next time we introduce such a bug because it will violate the Unique Constraint.</p>
  
  <p>But it is of course hacky, and I'm still pretty scared ;P 
  Are there any better ways to prevent whole tree's of cached objects ending up in the database?</p>
  
  <p><strong>More information</strong></p>
  
  <ul>
  <li>Project is ASP.NET MVC </li>
  <li>I cache this data, because it is mainly read only, and this saves a tons of extra database calls per http request</li>
  <li>This is in a high traffic website, with a lot of personal customized views. Having the POCO data in memory works really good for what I want. Except the problem I mentioned.</li>
  <li>It is a bit more complicated, but a simplified version is that I cache the objects by a singleton: so i.e:</li>
  </ul>
  
  <p><code>EntityCache.Instance.LolCats = new DbContext().LolCats.AsNoTracking().ToList();</code></p>
  
  <p>This cache I dependency-inject into my controllers.</p>