Search code examples
c#entity-frameworkcachingcache-invalidation

Entity Framework DbContext detect changes from outside


I'm sure this is a duplicate but I can't find the question after scouring the internet. So if this is a duplicate, please just point me to the right one.

Question: How can I get entity framework to pickup changes in an entity in the database that happened from another source.

I have had many issues with this type of thing because of the DbContext cache not being updated.

Example: Suppose I have 2 servers with the same schema. Both servers work together and both use the table Person.

  1. Server A creates Person Jack with an age of 21, saving it to the DB. Jack is cached in Server A's DbContext.
  2. Server B fetches Jack from the DB after Server A creates it. Then, Server B updates Jack to up the age to 22, saving it to the DB.
  3. A request for Jack is made to Server A. So Server A's DbContext responds with the version of Jack that is in it's cache... with age still at 21.

I find it hard to believe that there's not a way for Server A's DbContext to re-fetch the record. I feel like this ability should be baked in to Entity Framework. If not, then what are my other options?

One option I thought of was to just tell Entity Framework not to use the cache. Is this possible?


Solution

  • I think you using your DbContext as a singleton instance. In case you initialize your DbContext each time it's called this issue will not occure. But more you can find more details about it here.