Concurrent access to a database with Entity Framework == EntityException Concurrent access to a database with Entity Framework == EntityException multithreading multithreading

Concurrent access to a database with Entity Framework == EntityException


Without seeing your code, the short answer is that EntityFramework is not thread-safe. You're getting this error in a seemingly random pattern when two+ threads overlap when trying to try access your ObjectContext. I assume you've stuffed your context into a static variable. Either make the context a local variable or write locking around access to the ObjectContext.

If you want a more specific answer posting your code will help.

Edit

Your issue is that two threads are trying to use the context at the same time, or 1 thread is leaving a transaction open then and a second thread comes through trying to use your singleton context. Your code snippet raises more questions for me than I had before.

  • In your code example is _lockObject a static variable?
  • Why do you show the lock in SaveChanges but then explain an error is being thrownfrom InsertOrUpdateDetachedObject? Can we see the code for InsertOrUpdateDetachedObject?
  • Does SaveChanges use the same _lockObject as all other methods that access the context directly?
  • Is your call to _context.SaveChanges the only way you save to the DB or do you have other areas that open transaction contexts on their own?
  • Your using a singleton so your context is shared across multiple calls. It might be preferable to instantiate a new new context for every WFC call.