views:

44

answers:

1

I am working on my first large project that uses EF4 and have been pondering concurrency situations as I am implementing certain business scenarios. I understand that EF has built in support for optimistic concurrency by setting Concurrency Mode to Fixed on entity properties. This seems to be sufficient in most cases. Several things I am wondering about:

  1. In a situation where I first validate that an entity does not exist, then subsequently insert the entity. Technically someone could have inserted that entity in the split second between my validation and my insert. What is the best practice to handle this scenario with EF? Naturally I am thinking about two possible solutions, pessimistic concurrency or handling a unique constraint exception that will occur.

  2. I am trying to remember if issuing a Begin Transaction/Commit Transaction block in SQL will automatically lock the tables involved, meaning it will force the pessimistic scenario I alluded to above. If so, will wrapping these two EF operations in TransactionScope achieve similar results?

  3. If TransactionScope will not force pessimistic concurrency, what will?

+1  A: 
  1. A DB constraint is the only reliable solution to this, because it's the only solution which can see uncommitted transactions from other writers.
  2. Don't presume that SQL Server is locking tables. It might be locking rows.
  3. Lingering, uncommitted writes. Which are usually a bad idea with any data access technology. Use constraints instead.

Why would you want to use TransactionScope when not using multiple contexts? Well, maybe you need to get a server-generated key in the course of one transaction (think SCOPE_IDENTITY). In general, when you have multiple calls to SaveChanges() which must succeed or fail as a group.

Craig Stuntz
I guess I would have to find a good example to why I would want to make multiple calls to SaveChanges() within one context/transaction. I suppose it's probably more common in a stateful environment as opposed to ASP.NET which is is really mostly request scoped. I am not sure I understand your point #3. There are places where pessimistic concurrency has it's place. I am wondering if it's at all possible with EF 4. Or should I take your point #1 as no there isn't and like you said watching for constraint violations is the only way to go?
e36M3
#3 is possible with `TransactionScope`. But it doesn't actually solve your problem due to #1.
Craig Stuntz
Understood. So to confirm TransactionScope will in fact start locking rows/tables but only on modified rows (pessimistic concurrency). Therefor it does nothing for me between the initial validation up to the insert.
e36M3