Handling Concurrency with the Entity Framework in an ASP.NET MVC Application (7 of 10)
by Tom Dykstra
The Contoso University sample web application demonstrates how to create ASP.NET MVC 4 applications using the Entity Framework 5 Code First and Visual Studio 2012. For information about the tutorial series, see the first tutorial in the series. You can start the tutorial series from the beginning or download a starter project for this chapter and start here.
[!NOTE]
If you run into a problem you can’t resolve, download the completed chapter and try to reproduce your problem. You can generally find the solution to the problem by comparing your code to the completed code. For some common errors and how to solve them, see Errors and Workarounds.
In the previous two tutorials you worked with related data. This tutorial shows how to handle concurrency. You’ll create web pages that work with the Department
entity, and the pages that edit and delete Department
entities will handle concurrency errors. The following illustrations show the Index and Delete pages, including some messages that are displayed if a concurrency conflict occurs.
Concurrency Conflicts
A concurrency conflict occurs when one user displays an entity’s data in order to edit it, and then another user updates the same entity’s data before the first user’s change is written to the database. If you don’t enable the detection of such conflicts, whoever updates the database last overwrites the other user’s changes. In many applications, this risk is acceptable: if there are few users, or few updates, or if isn’t really critical if some changes are overwritten, the cost of programming for concurrency might outweigh the benefit. In that case, you don’t have to configure the application to handle concurrency conflicts.
Pessimistic Concurrency (Locking)
If your application does need to prevent accidental data loss in concurrency scenarios, one way to do that is to use database locks. This is called pessimistic concurrency. For example, before you read a row from a database, you request a lock for read-only or for update access. If you lock a row for update access, no other users are allowed to lock the row either for read-only or update access, because they would get a copy of data that’s in the process of being changed. If you lock a row for read-only access, others can also lock it for read-only access but not for update.
Managing locks has disadvantages. It can be complex to program. It requires significant database management resources, and it can cause performance problems as the number of users of an application increases (that is, it doesn’t scale well). For these reasons, not all database management systems support pessimistic concurrency. The Entity Framework provides no built-in support for it, and this tutorial doesn’t show you how to implement it.
Optimistic Concurrency
The alternative to pessimistic concurrency is optimistic concurrency. Optimistic concurrency means allowing concurrency conflicts to happen, and then reacting appropriately if they do. For example, John runs the Departments Edit page, changes the Budget amount for the English department from $350,000.00 to $0.00.
Before John clicks Save, Jane runs the same page and changes the Start Date field from 9/1/2007 to 8/8/2013.
John clicks Save first and sees his change when the browser returns to the Index page, then Jane clicks Save. What happens next is determined by how you handle concurrency conflicts. Some of the options include the following:
You can keep track of which property a user has modified and update only the corresponding columns in the database. In the example scenario, no data would be lost, because different properties were updated by the two users. The next time someone browses the English department, they’ll see both John’s and Jane’s changes — a start date of 8/8/2013 and a budget of Zero dollars.
This method of updating can reduce the number of conflicts that could result in data loss, but it can’t avoid data loss if competing changes are made to the same property of an entity. Whether the Entity Framework works this way depends on how you implement your update code. It’s often not practical in a web application, because it can require that you maintain large amounts of state in order to keep track of all original property values for an entity as well as new values. Maintaining large amounts of state can affect application performance because it either requires server resources or must be included in the web page itself (for example, in hidden fields).- You can let Jane’s change overwrite John’s change. The next time someone browses the English department, they’ll see 8/8/2013 and the restored $350,000.00 value. This is called a Client Wins or Last in Wins scenario. (The client’s values take precedence over what’s in the data store.) As noted in the introduction to this section, if you don’t do any coding for concurrency handling, this will happen automatically.
You can prevent Jane’s change from being updated in the database. Typically, you would display an error message, show her the current state of the data, and allow her to reapply her changes if she still wants to make them. This is called a Store Wins scenario. (The data-store values take precedence over the values submitted by the client.) You’ll implement the Store Wins scenario in this tutorial. This method ensures that no changes are overwritten without a user being alerted to what’s happening.
Detecting Concurrency Conflicts
You can resolve conflicts by handling OptimisticConcurrencyException exceptions that the Entity Framework throws. In order to know when to throw these exceptions, the Entity Framework must be able to detect conflicts. Therefore, you must configure the database and the data model appropriately. Some options for enabling conflict detection include the following:
In the database table, include a tracking column that can be used to determine when a row has been changed. You can then configure the Entity Framework to include that column in the
The data type of the tracking column is typically rowversion. The rowversion value is a sequential number that’s incremented each time the row is updated. In anWhere
clause of SQLUpdate
orDelete
commands.Update
orDelete
command, theWhere
clause includes the original value of the tracking column (the original row version). If the row being updated has been changed by another user, the value in therowversion
column is different than the original value, so theUpdate
orDelete
statement can’t find the row to update because of theWhere
clause. When the Entity Framework finds that no rows have been updated by theUpdate
orDelete
command (that is, when the number of affected rows is zero), it interprets that as a concurrency conflict.Configure the Entity Framework to include the original values of every column in the table in the
Where
clause ofUpdate
andDelete
commands.As in the first option, if anything in the row has changed since the row was first read, the
Where
clause won’t return a row to update, which the Entity Framework interprets as a concurrency conflict. For database tables that have many columns, this approach can result in very largeWhere
clauses, and can require that you maintain large amounts of state. As noted earlier, maintaining large amounts of state can affect application performance because it either requires server resources or must be included in the web page itself. Therefore this approach generally not recommended, and it isn’t the method used in this tutorial.If you do want to implement this approach to concurrency, you have to mark all non-primary-key properties in the entity you want to track concurrency for by adding the ConcurrencyCheck attribute to them. That change enables the Entity Framework to include all columns in the SQL
WHERE
clause ofUPDATE
statements.
In the remainder of this tutorial you’ll add a rowversion tracking property to the Department
entity, create a controller and views, and test to verify that everything works correctly.
Add an Optimistic Concurrency Property to the Department Entity
In Models.cs, add a tracking property named RowVersion
:
[!code-csharpMain]
1: public class Department
2: {
3: public int DepartmentID { get; set; }
4:
5: [StringLength(50, MinimumLength = 3)]
6: public string Name { get; set; }
7:
8: [DataType(DataType.Currency)]
9: [Column(TypeName = "money")]
10: public decimal Budget { get; set; }
11:
12: [DataType(DataType.Date)]
13: public DateTime StartDate { get; set; }
14:
15: [Display(Name = "Administrator")]
16: public int? InstructorID { get; set; }
17:
18: [Timestamp]
19: public byte[] RowVersion { get; set; }
20:
21: public virtual Instructor Administrator { get; set; }
22: public virtual ICollection<Course> Courses { get; set; }
23: }
The Timestamp attribute specifies that this column will be included in the Where
clause of Update
and Delete
commands sent to the database. The attribute is called Timestamp because previous versions of SQL Server used a SQL timestamp data type before the SQL rowversion replaced it. The .Net type for rowversion
is a byte array. If you prefer to use the fluent API, you can use the IsConcurrencyToken method to specify the tracking property, as shown in the following example:
[!code-csharpMain]
1: modelBuilder.Entity<Department>()
2: .Property(p => p.RowVersion).IsConcurrencyToken();
By adding a property you changed the database model, so you need to do another migration. In the Package Manager Console (PMC), enter the following commands:
[!code-consoleMain]
1: Add-Migration RowVersion
2: Update-Database
Create a Department Controller
Create a Department
controller and views the same way you did the other controllers, using the following settings:
In Controllers.cs, add a using
statement:
[!code-csharpMain]
1: using System.Data.Entity.Infrastructure;
Change “LastName” to “FullName” everywhere in this file (four occurrences) so that the department administrator drop-down lists will contain the full name of the instructor rather than just the last name.
[!code-csharpMain]
1: ViewBag.InstructorID = new SelectList(db.Instructors, "InstructorID", "FullName");
Replace the existing code for the HttpPost
Edit
method with the following code:
[!code-csharpMain]
1: [HttpPost]
2: [ValidateAntiForgeryToken]
3: public ActionResult Edit(
4: [Bind(Include = "DepartmentID, Name, Budget, StartDate, RowVersion, InstructorID")]
5: Department department)
6: {
7: try
8: {
9: if (ModelState.IsValid)
10: {
11: db.Entry(department).State = EntityState.Modified;
12: db.SaveChanges();
13: return RedirectToAction("Index");
14: }
15: }
16: catch (DbUpdateConcurrencyException ex)
17: {
18: var entry = ex.Entries.Single();
19: var clientValues = (Department)entry.Entity;
20: var databaseValues = (Department)entry.GetDatabaseValues().ToObject();
21:
22: if (databaseValues.Name != clientValues.Name)
23: ModelState.AddModelError("Name", "Current value: "
24: + databaseValues.Name);
25: if (databaseValues.Budget != clientValues.Budget)
26: ModelState.AddModelError("Budget", "Current value: "
27: + String.Format("{0:c}", databaseValues.Budget));
28: if (databaseValues.StartDate != clientValues.StartDate)
29: ModelState.AddModelError("StartDate", "Current value: "
30: + String.Format("{0:d}", databaseValues.StartDate));
31: if (databaseValues.InstructorID != clientValues.InstructorID)
32: ModelState.AddModelError("InstructorID", "Current value: "
33: + db.Instructors.Find(databaseValues.InstructorID).FullName);
34: ModelState.AddModelError(string.Empty, "The record you attempted to edit "
35: + "was modified by another user after you got the original value. The "
36: + "edit operation was canceled and the current values in the database "
37: + "have been displayed. If you still want to edit this record, click "
38: + "the Save button again. Otherwise click the Back to List hyperlink.");
39: department.RowVersion = databaseValues.RowVersion;
40: }
41: catch (DataException /* dex */)
42: {
43: //Log the error (uncomment dex variable name after DataException and add a line here to write a log.
44: ModelState.AddModelError(string.Empty, "Unable to save changes. Try again, and if the problem persists contact your system administrator.");
45: }
46:
47: ViewBag.InstructorID = new SelectList(db.Instructors, "InstructorID", "FullName", department.InstructorID);
48: return View(department);
49: }
The view will store the original RowVersion
value in a hidden field. When the model binder creates the department
instance, that object will have the original RowVersion
property value and the new values for the other properties, as entered by the user on the Edit page. Then when the Entity Framework creates a SQL UPDATE
command, that command will include a WHERE
clause that looks for a row that has the original RowVersion
value.
If no rows are affected by the UPDATE
command (no rows have the original RowVersion
value), the Entity Framework throws a DbUpdateConcurrencyException
exception, and the code in the catch
block gets the affected Department
entity from the exception object. This entity has both the values read from the database and the new values entered by the user:
[!code-csharpMain]
1: var entry = ex.Entries.Single();
2: var clientValues = (Department)entry.Entity;
3: var databaseValues = (Department)entry.GetDatabaseValues().ToObject();
Next, the code adds a custom error message for each column that has database values different from what the user entered on the Edit page:
[!code-csharpMain]
1: if (databaseValues.Name != currentValues.Name)
2: ModelState.AddModelError("Name", "Current value: " + databaseValues.Name);
3: // ...
A longer error message explains what happened and what to do about it:
[!code-csharpMain]
1: ModelState.AddModelError(string.Empty, "The record you attempted to edit "
2: + "was modified by another user after you got the original value. The"
3: + "edit operation was canceled and the current values in the database "
4: + "have been displayed. If you still want to edit this record, click "
5: + "the Save button again. Otherwise click the Back to List hyperlink.");
Finally, the code sets the RowVersion
value of the Department
object to the new value retrieved from the database. This new RowVersion
value will be stored in the hidden field when the Edit page is redisplayed, and the next time the user clicks Save, only concurrency errors that happen since the redisplay of the Edit page will be caught.
In Views.cshtml, add a hidden field to save the RowVersion
property value, immediately following the hidden field for the DepartmentID
property:
[!code-cshtmlMain]
1: @model ContosoUniversity.Models.Department
2:
3: @{
4: ViewBag.Title = "Edit";
5: }
6:
7: <h2>Edit</h2>
8:
9: @using (Html.BeginForm()) {
10: @Html.AntiForgeryToken()
11: @Html.ValidationSummary(true)
12:
13: <fieldset>
14: <legend>Department</legend>
15:
16: @Html.HiddenFor(model => model.DepartmentID)
17: @Html.HiddenFor(model => model.RowVersion)
18:
19: <div class="editor-label">
20: @Html.LabelFor(model => model.Name)
21: </div>
In Views.cshtml, replace the existing code with the following code to move row links to the left and change the page title and column headings to display FullName
instead of LastName
in the Administrator column:
[!code-cshtmlMain]
1: @model IEnumerable<ContosoUniversity.Models.Department>
2:
3: @{
4: ViewBag.Title = "Departments";
5: }
6:
7: <h2>Departments</h2>
8:
9: <p>
10: @Html.ActionLink("Create New", "Create")
11: </p>
12: <table>
13: <tr>
14: <th></th>
15: <th>Name</th>
16: <th>Budget</th>
17: <th>Start Date</th>
18: <th>Administrator</th>
19: </tr>
20:
21: @foreach (var item in Model) {
22: <tr>
23: <td>
24: @Html.ActionLink("Edit", "Edit", new { id=item.DepartmentID }) |
25: @Html.ActionLink("Details", "Details", new { id=item.DepartmentID }) |
26: @Html.ActionLink("Delete", "Delete", new { id=item.DepartmentID })
27: </td>
28: <td>
29: @Html.DisplayFor(modelItem => item.Name)
30: </td>
31: <td>
32: @Html.DisplayFor(modelItem => item.Budget)
33: </td>
34: <td>
35: @Html.DisplayFor(modelItem => item.StartDate)
36: </td>
37: <td>
38: @Html.DisplayFor(modelItem => item.Administrator.FullName)
39: </td>
40: </tr>
41: }
42:
43: </table>
Testing Optimistic Concurrency Handling
Run the site and click Departments:
Right click the Edit hyperlink for Kim Abercrombie and select Open in new tab, then click the Edit hyperlink for Kim Abercrombie. The two windows display the same information.
Change a field in the first browser window and click Save.
The browser shows the Index page with the changed value.
Change the any field in the second browser window and click Save.
Click Save in the second browser window. You see an error message:
Click Save again. The value you entered in the second browser is saved along with the original value of the data you change in the first browser. You see the saved values when the Index page appears.
Updating the Delete Page
For the Delete page, the Entity Framework detects concurrency conflicts caused by someone else editing the department in a similar manner. When the HttpGet
Delete
method displays the confirmation view, the view includes the original RowVersion
value in a hidden field. That value is then available to the HttpPost
Delete
method that’s called when the user confirms the deletion. When the Entity Framework creates the SQL DELETE
command, it includes a WHERE
clause with the original RowVersion
value. If the command results in zero rows affected (meaning the row was changed after the Delete confirmation page was displayed), a concurrency exception is thrown, and the HttpGet Delete
method is called with an error flag set to true
in order to redisplay the confirmation page with an error message. It’s also possible that zero rows were affected because the row was deleted by another user, so in that case a different error message is displayed.
In DepartmentController.cs, replace the HttpGet
Delete
method with the following code:
[!code-csharpMain]
1: public ActionResult Delete(int id, bool? concurrencyError)
2: {
3: Department department = db.Departments.Find(id);
4:
5: if (concurrencyError.GetValueOrDefault())
6: {
7: if (department == null)
8: {
9: ViewBag.ConcurrencyErrorMessage = "The record you attempted to delete "
10: + "was deleted by another user after you got the original values. "
11: + "Click the Back to List hyperlink.";
12: }
13: else
14: {
15: ViewBag.ConcurrencyErrorMessage = "The record you attempted to delete "
16: + "was modified by another user after you got the original values. "
17: + "The delete operation was canceled and the current values in the "
18: + "database have been displayed. If you still want to delete this "
19: + "record, click the Delete button again. Otherwise "
20: + "click the Back to List hyperlink.";
21: }
22: }
23:
24: return View(department);
25: }
The method accepts an optional parameter that indicates whether the page is being redisplayed after a concurrency error. If this flag is true
, an error message is sent to the view using a ViewBag
property.
Replace the code in the HttpPost
Delete
method (named DeleteConfirmed
) with the following code:
[!code-csharpMain]
1: [HttpPost]
2: [ValidateAntiForgeryToken]
3: public ActionResult Delete(Department department)
4: {
5: try
6: {
7: db.Entry(department).State = EntityState.Deleted;
8: db.SaveChanges();
9: return RedirectToAction("Index");
10: }
11: catch (DbUpdateConcurrencyException)
12: {
13: return RedirectToAction("Delete", new { concurrencyError=true } );
14: }
15: catch (DataException /* dex */)
16: {
17: //Log the error (uncomment dex variable name after DataException and add a line here to write a log.
18: ModelState.AddModelError(string.Empty, "Unable to delete. Try again, and if the problem persists contact your system administrator.");
19: return View(department);
20: }
21: }
In the scaffolded code that you just replaced, this method accepted only a record ID:
[!code-csharpMain]
1: public ActionResult DeleteConfirmed(int id)
You’ve changed this parameter to a Department
entity instance created by the model binder. This gives you access to the RowVersion
property value in addition to the record key.
[!code-csharpMain]
1: public ActionResult Delete(Department department)
You have also changed the action method name from DeleteConfirmed
to Delete
. The scaffolded code named the HttpPost
Delete
method DeleteConfirmed
to give the HttpPost
method a unique signature. (The CLR requires overloaded methods to have different method parameters.) Now that the signatures are unique, you can stick with the MVC convention and use the same name for the HttpPost
and HttpGet
delete methods.
If a concurrency error is caught, the code redisplays the Delete confirmation page and provides a flag that indicates it should display a concurrency error message.
In Views.cshtml, replace the scaffolded code with the following code that makes some formatting changes and adds an error message field. The changes are highlighted.
[!code-cshtmlMain]
1: @model ContosoUniversity.Models.Department
2:
3: @{
4: ViewBag.Title = "Delete";
5: }
6:
7: <h2>Delete</h2>
8:
9: <p class="error">@ViewBag.ConcurrencyErrorMessage</p>
10:
11: <h3>Are you sure you want to delete this?</h3>
12: <fieldset>
13: <legend>Department</legend>
14:
15: <div class="display-label">
16: @Html.DisplayNameFor(model => model.Name)
17: </div>
18: <div class="display-field">
19: @Html.DisplayFor(model => model.Name)
20: </div>
21:
22: <div class="display-label">
23: @Html.DisplayNameFor(model => model.Budget)
24: </div>
25: <div class="display-field">
26: @Html.DisplayFor(model => model.Budget)
27: </div>
28:
29: <div class="display-label">
30: @Html.DisplayNameFor(model => model.StartDate)
31: </div>
32: <div class="display-field">
33: @Html.DisplayFor(model => model.StartDate)
34: </div>
35:
36: <div class="display-label">
37: @Html.DisplayNameFor(model => model.Administrator.FullName)
38: </div>
39: <div class="display-field">
40: @Html.DisplayFor(model => model.Administrator.FullName)
41: </div>
42: </fieldset>
43: @using (Html.BeginForm()) {
44: @Html.AntiForgeryToken()
45: @Html.HiddenFor(model => model.DepartmentID)
46: @Html.HiddenFor(model => model.RowVersion)
47: <p>
48: <input type="submit" value="Delete" /> |
49: @Html.ActionLink("Back to List", "Index")
50: </p>
51: }
This code adds an error message between the h2
and h3
headings:
[!code-cshtmlMain]
1: <p class="error">@ViewBag.ConcurrencyErrorMessage</p>
It replaces LastName
with FullName
in the Administrator
field:
[!code-cshtmlMain]
1: <div class="display-label">
2: @Html.LabelFor(model => model.InstructorID)
3: </div>
4: <div class="display-field">
5: @Html.DisplayFor(model => model.Administrator.FullName)
6: </div>
Finally, it adds hidden fields for the DepartmentID
and RowVersion
properties after the Html.BeginForm
statement:
[!code-cshtmlMain]
1: @Html.HiddenFor(model => model.DepartmentID)
2: @Html.HiddenFor(model => model.RowVersion)
Run the Departments Index page. Right click the Delete hyperlink for the English department and select Open in new window, then in the first window click the Edit hyperlink for the English department.
In the first window, change one of the values, and click Save :
The Index page confirms the change.
In the second window, click Delete.
You see the concurrency error message, and the Department values are refreshed with what’s currently in the database.
If you click Delete again, you’re redirected to the Index page, which shows that the department has been deleted.
Summary
This completes the introduction to handling concurrency conflicts. For information about other ways to handle various concurrency scenarios, see Optimistic Concurrency Patterns and Working with Property Values on the Entity Framework team blog. The next tutorial shows how to implement table-per-hierarchy inheritance for the Instructor
and Student
entities.
Links to other Entity Framework resources can be found in the ASP.NET Data Access Content Map.
|