0

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?

Ian Kirkpatrick
  • 1,861
  • 14
  • 33
  • 3
    Usually the DbContext would be so short lived this isn't a much of a problem? This might be helpful - https://learn.microsoft.com/en-us/ef/core/saving/concurrency – Sam Aug 22 '19 at 16:19

1 Answers1

0

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.

turanszkik
  • 494
  • 5
  • 15
  • I just modified my question, specifically the steps in the scanario. I think you may have misunderstood it. Jack is one row in the Database but there's two servers with their own DbContext and therefore, their own object of Jack in memory. Assume the two servers don't even know eachother exist. – Ian Kirkpatrick Aug 22 '19 at 17:07
  • @IanKirkpatrick Oh now I understand your problem I updated my answer. – turanszkik Aug 22 '19 at 17:18
  • If you get rid of everything after the `Edit` part I will mark this as accepted. Thank you. – Ian Kirkpatrick Aug 23 '19 at 16:40