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.
- Disable Tracking using
- Throw away the
DbContextand create a new one
- Use an
ObjectQueryinstead of a
- Refresh the Entities
- Detatch the Entities
- Call GetDatabaseValues to get the updated values for a single Entity
- Use the stale data
Code related to this post can be found at https://github.com/codethug/EFCaching