Back to EF FAQs Table of Contents

How do I properly handle concurrency


The Entity Framework has built-in support for optimistic concurrency. This means that if you properly attribute your entity property metadata to indicate which property should act as the concurrency token (meaning whenever a part of the entity changes this property will also change--it could be a version number or timestamp or something), when you change an entity's properties and then call SaveChanges on the ObjectContext, the EF will check to make sure that the concurrency token has not changed since you last retrieved the entity.

When you call SaveChanges, all operations occur within a database transaction, so if a concurrency token change or other problem occurs, the transaction will be rolled back, the objects will remain in the context in basically the same state they were in when you called SaveChanges and an exception will be thrown. This allows you to make changes to the conflicting objects so the save can be attempted again. You can use the Refresh method to update the objects, or execute a query with either MergeOption PreserveChanges or OverwriteChanges, depending on what you want do to with the changes you have made on the client. These types of queries are essentially what Refresh does, but Refresh is a bit simpler--particularly when you need to update specific individual objects. More on concurrency here: Saving changes and managing concurrency

The following blog posts talk about concurrency and model first:
The following blog posts talk about managing optimistic concurrency updates in n-tier applications:
The following tutorials explain how to handle concurrency in ASP.NET web applications:
Additional resources:

 

How does concurrency work when there is inheritance and the concurrency column is on the parent table, while the child table's properties were modified


Whenever any part of an entity that has a concurrency token is modified, the update system of the Entity Framework guarantees that the table with the concurrency value is "touched". In cases where there isn't a real modification being made, a fake update statement is issued that doesn't change anything but does force the rowversion to update.
Back to EF FAQs Table of Contents