How should I handle this Optimistic Concurrency error in this Entity Framework code, I have?

Posted by Pure.Krome on Stack Overflow See other posts from Stack Overflow or by Pure.Krome
Published on 2010-03-31T13:27:30Z Indexed on 2010/04/01 3:43 UTC
Read the original article Hit count: 317

Hi folks,

I have the following pseduo code in some Repository Pattern project that uses EF4.

public void Delete(int someId)
{
   // 1. Load the entity for that Id. If there is none, then null.
   // 2. If entity != null, then DeleteObject(..);
}

Pretty simple but I'm getting a run-time error:-

ConcurrencyException: Store, Update, Insert or Delete statement affected an unexpected number of rows (0).

Now, this is what is happening :-

  1. Two instances of EF4 are running inthe app at the same time.
  2. Instance A calls delete.
  3. Instance B calls delete a nano second later.
  4. Instance A loads the entity.
  5. Instance B also loads the entity.
  6. Instance A now deletes that entity - cool bananas.
  7. Instance B tries to delete the entity, but it's already gone. As such, the no-count or what not is 0, when it expected 1 .. or something like that. Basically, it figured out that the item it is suppose to delete, didn't delete (because it happened a split sec ago).

I'm not sure if this is like a race-condition or something.

Anyways, is there any tricks I can do here so the 2nd call doesn't crash? I could make it into a stored procedure.. but I'm hoping to avoid that right now.

Any ideas? I'm wondering If it's possible to lock that row (and that row only) when the select is called ... forcing Instance B to wait until the row lock has been relased. By that time, the row is deleted, so when Instance B does it's select, the data is not there .. so it will never delete.

© Stack Overflow or respective owner

Related posts about .net-4.0

Related posts about entity-framework-4