Tuesday, 12 June 2012

Entity Framework - Concurrency

By default, the Entity Framework implements an optimistic concurrency model. This means that locks are not held on data in the data source between when the data is queried and the data is updated. The Entity Framework saves object changes to the database without checking for concurrency. For entities that might experience a high degree of concurrency, we recommend that the entity define a property in the conceptual layer with an attribute of ConcurrencyMode="fixed".

Follow the Following Steps to achive this in your implementation -

Step 1: Add a column to your table will type as timestamp. Here I have Added column with Name "rowversion".

Step 2: Open your Entity Model and Set the Concurreny Mode to "Fixed" of the rowversion column created in Step 1. See the screenshot.




Step 3: You can confirm the same in the .csdl file created by Code Generator at the following location.


 Step 4: Now you check the Query in the Profiler that It checks for the rowversion on update Query.



Note: The data type of the rowversion column is Timestamp. However, the column doesn't actually contain a date or time value. Instead, the value is a sequential number that's incremented each time the row is updated. In an Update or Delete command, the Where clause includes the original Timestamp value. If the row being updated has been changed by another user, the value in Timestamp is different than the original value, so the Where clause returns no row to update. When the Entity Framework finds that no rows have been updated by the current Update or Delete command (that is, when the number of affected rows is zero), it interprets that as a concurrency conflict.

No comments:

Post a Comment