Entity Framework Cache Busting

The DbContext in Entity Framework 6 automatically caches data that it retrieves from your database. This is useful, but sometimes data changes outside your context (perhaps by another user) and you end up with stale data. How can you force Entity Framework to reload the updated data from the database, and when should you do this?

There are several ways to manage this, depending on which version of Entity Framework you are using and what type of application you are writing.

  1. Disable Tracking using AsNoTracking()
  2. Throw away the DbContext and create a new one
  3. Use an ObjectQuery instead of a DBQuery and set MergeOptions
  4. Refresh the Entities
  5. Detatch the Entities
  6. Call GetDatabaseValues to get the updated values for a single Entity
  7. Use the stale data

Code related to this post can be found at https://github.com/codethug/EFCaching

Read More