We had a new contractor start the other day in work and he brought to my attention the ability to tell entity framework to not track (e.g. bypass the ObjectStateManager) the results of a query using the AsNoTracking method which if you are only loading entities once may result in a performance boost.
I’m not sure how I missed this one before but this method appears very useful when querying read only data which you might just be using to populate a drop down or similar HTML element for example. Examples of how AsNoTracking can be implemented are on the MSDN article ‘Performance Considerations for Entity Framework 4, 5, and 6‘
As that article points out however be mindful that bypassing the ObjectStateManager disables the cache and thus if you retrieve the same entities multiple times from the same context, using AsNoTracking could actually worsen the performance of your queries.
If you want to have a client-wins or last in wins approach to concurrency management you don’t have to do anything, the last user to save their changes will simply cause an overwrite of all previous changes. This is acceptable in many cases. You might however want to notify the user of the most recent save (attempted) that another user has saved changes to a record since they loaded the record edit page and thus their data is out of date and their update hasn’t been saved. This is refereed to as a store wins approach. Implementing this in Entity Framework is relatively easy, you need to:
Enable Entity Framework to detect optimistic concurrency violations
and when they happen catch DbUpdateConcurrencyException and notify user.
A common way to detect concurrency violations and the one recommended by Tom Dykstra is to use the rowversion data type approach. This data type is essentially a version stamp for a particular DB record. With this information, at the point of update (update or delete) client code (in this case entity framework) restricts the update or delete query with a where clause containing the original value of the rowversion field. If another user has edited the row, the where clause won’t match, 0 records will be update and Entity Framework will throw an exception. As noted in Tom’s article, to indicate to Entity Framework which field to use as the rowversion field you can annotate the relevant field with the [TimeStamp] annotation or use the fluent API.
This column of course must be manually created in the DB or migrated into the DB as with entity frameworks code first approach. Although for the purpose of the demo, Tom’s article has the C# property in the object class itself, it is often better to use an entity base class which can contain implementation fields such as RowVersion, DateCreated and DateModified. While doing this is still technically ‘polluting’ the domain model, it keeps things a little bit cleaner and is a good solution for most. Remember that you will need to post back the value of the RowVersion field using a hidden field for Entity Framework to work with it: @Html.HiddenFor(model => model.RowVersion).
Although the underlying exception thrown is OptimisticConcurrencyException, entity frameworks wrap of that is DbUpdateConcurrencyException, and this is the one you should catch after attempting calling SaveChanges() in your try block.
You can see from the above trimmed down excerpt from Tom Dykstra’s official MS article (Handling Concurrency with the Entity Framework 6 in an ASP.NET MVC 5 Application) that he sends the current DB values back to the GUI so the user can see what the previous user changed the values to. Since the rowversion which gets sent back to the view is updated with the DB rowversion value the user can now review the current values and then decide to keep his or her changes without causing another concurrency exception. Although this is a nice usability touch, it can be expensive to program all the explicit comparisons between the DB values and values from the GUI, particularly in large applications with a lot of edit pages. An alternative approach might be to simply reload the edit page, discard attempted updates and put a message informing (using TempData) the user that their changes didn’t go through. Of course the user has to redo their changes in this instance, but this approach could be fine if it is only rare that concurrency issues happen.
To keep things DRY you could put this code in a base controller method. If a concurrency exception is thrown in a delete controller action after a previous user has edited something, you can use a similar technique and redirect to the edit page and inform them they need to try and delete again. On the other hand if a user attempts to delete an already deleted record, I don’t think you need to display anything concurrency related on the GUI as the user has got what they wanted, just a regular confirmation perhaps.