0

I have MVC application hosted as Azure web role and I also have Worker role which checks some data and update records in database. Worker role checks data on every 15 minutes.

Yesterday, I went into big trouble because a lot of changes made via MVC application is just reverted.

I will try to give an example:

  1. User made changes on one entity yesterday (this is tracked by event log)

  2. In meantime, worker role updated that entity

  3. Today, user updated entity multiple time

  4. At the end, entity has data from yesterday, not from today

MVC application uses simple SaveChanges function while worker role uses BeginTransaction with SaveChanges.

I suspect on locking and isolation level, but it is strange that lock is almost 24h long.

I hope that someone will understand this and help me.

Thanks

Danilo Vulović
  • 2,847
  • 17
  • 28
  • Are you persisting the EF database context somewhere, like a property, or are you declaring a new one and then disposing for each DB operation? – Paul Abbott Oct 06 '15 at 21:27

1 Answers1

1

If you're keeping a persistent EF database context in your worker role, it's possible you're seeing the effects of EF objects being cached.

  1. Worker role loads an entity and does something with it. Since you're not creating and disposing the EF context each time, the entity stays cached.

  2. User saves the entity and the database gets updated with their changes.

  3. Worker role queries for the entity again, but since it's cached it returns the outdated, cached version. It does some sort of save operation, overwriting the user's edits with the cached values.

See Entity Framework and Connection Pooling, specifically,

When you use EF it by default loads each entity only once per context. The first query creates entity instace and stores it internally. Any subsequent query which requires entity with the same key returns this stored instance. If values in the data store changed you still receive the entity with values from the initial query.

Bottom line, you should never persist an EF database context for long periods of time. You may think of it as just an open database connection, but it is much more than that and "optimizing" things by keeping it around is a false savings and will cause bad things to happen. It's meant to be used in a UoW pattern where you create it, do what operations need to be done, and then dispose of it ASAP.

Community
  • 1
  • 1
Paul Abbott
  • 6,915
  • 3
  • 25
  • 42