Contoso University Web 应用演示了如何使用 EF Core 和 Visual Studio 创建 Razor Pages Web 应用。 若要了解系列教程,请参阅第一个教程。
如果遇到无法解决的问题,请下载已完成的应用,然后对比该代码与按教程所创建的代码。
本教程介绍如何处理多个用户并发更新同一实体时出现的冲突。
并发冲突
在以下情况下,会发生并发冲突:
- 用户导航到实体的编辑页面。
- 第一个用户的更改还未写入数据库之前,另一用户更新同一实体。
如果未启用并发检测,则最后更新数据库的人员将覆盖其他用户的更改。 如果这种风险是可以接受的,则并发编程的成本可能会超过收益。
悲观并发控制
预防并发冲突的一种方法是使用数据库锁定。 这称为悲观并发。 应用在读取要更新的数据库行之前,将请求锁定。 锁定某一行的更新访问权限之后,其他用户在第一个锁定释放之前无法锁定该行。
管理锁定有缺点。 它的编程可能很复杂,并且随着用户增加可能会导致性能问题。 Entity Framework Core 不提供对悲观并发的内置支持。
乐观并发
乐观并发允许发生并发冲突,并在并发冲突发生时作出正确反应。 例如,Jane 访问院系编辑页面,将英语系的预算从 350,000.00 美元更改为 0.00 美元。
在 Jane 单击“保存”之前,John 访问了相同页面,并将开始日期字段从 2007/1/9 更改为 2013/1/9。
Jane 单击“保存”后看到更改生效,因为浏览器会显示预算金额为零的“索引”页面。
John 单击“编辑”页面上的“保存”,但页面的预算仍显示为 350,000.00 美元。 接下来的情况取决于并发冲突的处理方式:
跟踪用户已修改的属性,并仅更新数据库中相应的列。
在这种情况下,数据不会丢失。 两个用户更新了不同的属性。 下次有人浏览英语系时,将看到 Jane 和 John 两个人的更改。 这种更新方法可以减少可能导致数据丢失的冲突数量。 这种方法具有一些缺点:
- 无法避免数据丢失,如果对同一属性进行竞争性更改的话。
- 通常不适用于 Web 应用。 它需要维护大量状态信息,以跟踪所有获取到的值和新值。 维持大量状态可能影响应用性能。
- 与在实体上进行并发检测相比,这可能会增加应用程序的复杂性。
让 John 的更改覆盖 Jane 的更改。
下次有人浏览英语系时,将看到 2013/9/1 和提取的值 350,000.00 美元。 这种方法称为“客户端优先”或“最后一个优先”方案。 客户端的所有值优先于数据存储的值。 基架代码不处理并发,“客户端优先”方案会自动执行。
阻止在数据库中更新 John 的更改。 应用通常会:
- 显示错误消息。
- 显示数据的当前状态。
- 允许用户重新应用更改。
这称为“Store Wins”方案。 数据存储值优先于客户端提交的值。 本教程中使用了“存储优先”方案。 该方法可确保在未提醒用户的情况下,任何更改都不会被覆盖。
EF Core 中的冲突检测
使用配置为并发令牌的属性实现乐观并发控制。 当 SaveChanges 或 SaveChangesAsync 触发更新或删除操作时,数据库中的并发标记值将与 EF Core 读取的原始值进行比较:
- 如果这些值匹配,则可以完成该操作。
- 如果这些值不匹配,EF Core 会假设另一个用户已执行冲突操作,然后会中止当前事务,并引发 DbUpdateConcurrencyException。
另一个用户或进程执行与当前操作冲突的操作,这种情况称为“并发冲突”。
在关系数据库中,EF Core 会在 UPDATE 和 DELETE 语句的 WHERE 子句中检查并发标记的值,以检测并发冲突。
必须将数据模型配置为启用冲突检测,方法是包括一个可用于确定行更改时间的跟踪列。 EF 提供两种使用并发标记的方法:
将
[ConcurrencyCheck]或 IsConcurrencyToken 应用于模型上的属性。 不建议使用此方法。 有关详细信息,请参阅 EF Core 中的并发标记。将 TimestampAttribute 或 IsRowVersion 应用于模型中的并发标记。 本教程中使用了此方法。
SQL Server 的方案与 SQLite 的实现细节略有不同。 本教程的后续部分将提供一个差异文件,其中列出了这些差异。 Visual Studio 选项卡提供 SQL Server 方法。 Visual Studio Code 选项卡显示了针对非 SQL Server 数据库(例如 SQLite)的方法。
- 在模型中包含一个用于确定某行更改时间的跟踪列。
- 将 TimestampAttribute 应用于并发属性。
使用下面突出显示的代码更新 Models/Department.cs 文件:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ContosoUniversity.Models
{
public class Department
{
public int DepartmentID { get; set; }
[StringLength(50, MinimumLength = 3)]
public string Name { get; set; }
[DataType(DataType.Currency)]
[Column(TypeName = "money")]
public decimal Budget { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}",
ApplyFormatInEditMode = true)]
[Display(Name = "Start Date")]
public DateTime StartDate { get; set; }
public int? InstructorID { get; set; }
[Timestamp]
public byte[] ConcurrencyToken { get; set; }
public Instructor Administrator { get; set; }
public ICollection<Course> Courses { get; set; }
}
}
TimestampAttribute 用于标识该列为并发跟踪列。 Fluent API 是指定跟踪属性的另一种方式:
modelBuilder.Entity<Department>()
.Property<byte[]>("ConcurrencyToken")
.IsRowVersion();
应用于实体属性上的 [Timestamp] 特性会在 ModelBuilder 方法中生成以下代码:
b.Property<byte[]>("ConcurrencyToken")
.IsConcurrencyToken()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("rowversion");
前面的代码:
- 将属性类型
ConcurrencyToken设置为字节数组类型。byte[]是 SQL Server 所需的类型。 - 调用 IsConcurrencyToken。
IsConcurrencyToken将属性配置为并发令牌。 执行更新时,数据库中的并发标记值将与原始值进行比较,以确保从数据库检索到该实例之后它未发生更改。 若它已发生更改,将引发 DbUpdateConcurrencyException,并且不会应用更改。 - 调用 ValueGeneratedOnAddOrUpdate,它会将
ConcurrencyToken属性配置为在添加或更新实体时自动生成值。 -
HasColumnType("rowversion")将SQL Server数据库中的列类型设置为 rowversion。
以下代码显示更新 Department 名称时由 EF Core 生成的部分 T-SQL:
SET NOCOUNT ON;
UPDATE [Departments] SET [Name] = @p0
WHERE [DepartmentID] = @p1 AND [ConcurrencyToken] = @p2;
SELECT [ConcurrencyToken]
FROM [Departments]
WHERE @@ROWCOUNT = 1 AND [DepartmentID] = @p1;
前面突出显示的代码显示包含 ConcurrencyToken 的 WHERE 子句。 如果数据库 ConcurrencyToken 不等于 ConcurrencyToken 参数 @p2 的值,则不会更新任何行。
以下突出显示的代码显示了用于验证恰好更新了一行的 T-SQL:
SET NOCOUNT ON;
UPDATE [Departments] SET [Name] = @p0
WHERE [DepartmentID] = @p1 AND [ConcurrencyToken] = @p2;
SELECT [ConcurrencyToken]
FROM [Departments]
WHERE @@ROWCOUNT = 1 AND [DepartmentID] = @p1;
@@ROWCOUNT 返回受最后一个语句影响的行数。 如果没有更新行,EF Core 会引发 DbUpdateConcurrencyException。
添加迁移
添加 ConcurrencyToken 属性会更改数据模型,因此需要进行迁移。
构建项目。
在 PMC 中运行以下命令:
Add-Migration RowVersion
Update-Database
上述命令:
- 创建
Migrations/{time stamp}_RowVersion.cs迁移文件。 - 更新
Migrations/SchoolContextModelSnapshot.cs文件。 此次更新向BuildModel方法中添加了以下代码:
b.Property<byte[]>("ConcurrencyToken")
.IsConcurrencyToken()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("rowversion");
搭建“院系”页面的基架
按照Scaffold 学生页面中的说明操作,但以下情况除外:
- 创建 Pages/Departments 文件夹。
- 将
Department用于模型类。 - 使用现有的上下文类,而不是新建上下文类。
添加工具类
在项目文件夹中,使用以下代码创建 Utility 类:
namespace ContosoUniversity
{
public static class Utility
{
public static string GetLastChars(byte[] token)
{
return token[7].ToString();
}
}
}
Utility 类提供 GetLastChars 方法,用于显示并发标记的最后几个字符。 下面的代码展示了同时适用于 SQLite 和 SQL Server 的代码:
#if SQLiteVersion
using System;
namespace ContosoUniversity
{
public static class Utility
{
public static string GetLastChars(Guid token)
{
return token.ToString().Substring(
token.ToString().Length - 3);
}
}
}
#else
namespace ContosoUniversity
{
public static class Utility
{
public static string GetLastChars(byte[] token)
{
return token[7].ToString();
}
}
}
#endif
#if SQLiteVersion
预处理器指令隔离 SQLite 和 SQL Server 版本之间的差异,并帮助:
- 创作者维护一个同时用于这两个版本的代码库。
- SQLite 开发人员将应用部署到 Azure 并使用 SQL Azure。
构建项目。
更新“索引”页
基架工具为“索引”页创建了 ConcurrencyToken 列,但生产应用中不会显示该字段。 在本教程中,将显示 ConcurrencyToken 的最后一部分,以帮助说明并发处理是如何工作的。 无法保证最后一个部分本身是唯一的。
更新 Pages\Departments\Index.cshtml 页面:
- 用院系替换索引。
- 更改包含
ConcurrencyToken的代码,以便仅显示最后几个字符。 - 将
FirstMidName替换为FullName。
下面的代码展示了更新后的页面:
@page
@model ContosoUniversity.Pages.Departments.IndexModel
@{
ViewData["Title"] = "Departments";
}
<h2>Departments</h2>
<p>
<a asp-page="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Department[0].Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Department[0].Budget)
</th>
<th>
@Html.DisplayNameFor(model => model.Department[0].StartDate)
</th>
<th>
@Html.DisplayNameFor(model => model.Department[0].Administrator)
</th>
<th>
Token
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Department)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Budget)
</td>
<td>
@Html.DisplayFor(modelItem => item.StartDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Administrator.FullName)
</td>
<td>
@Utility.GetLastChars(item.ConcurrencyToken)
</td>
<td>
<a asp-page="./Edit" asp-route-id="@item.DepartmentID">Edit</a> |
<a asp-page="./Details" asp-route-id="@item.DepartmentID">Details</a> |
<a asp-page="./Delete" asp-route-id="@item.DepartmentID">Delete</a>
</td>
</tr>
}
</tbody>
</table>
更新编辑页模型
使用以下代码更新 Pages/Departments/Edit.cshtml.cs:
using ContosoUniversity.Data;
using ContosoUniversity.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading.Tasks;
namespace ContosoUniversity.Pages.Departments
{
public class EditModel : PageModel
{
private readonly ContosoUniversity.Data.SchoolContext _context;
public EditModel(ContosoUniversity.Data.SchoolContext context)
{
_context = context;
}
[BindProperty]
public Department Department { get; set; }
// Replace ViewData["InstructorID"]
public SelectList InstructorNameSL { get; set; }
public async Task<IActionResult> OnGetAsync(int id)
{
Department = await _context.Departments
.Include(d => d.Administrator) // eager loading
.AsNoTracking() // tracking not required
.FirstOrDefaultAsync(m => m.DepartmentID == id);
if (Department == null)
{
return NotFound();
}
// Use strongly typed data rather than ViewData.
InstructorNameSL = new SelectList(_context.Instructors,
"ID", "FirstMidName");
return Page();
}
public async Task<IActionResult> OnPostAsync(int id)
{
if (!ModelState.IsValid)
{
return Page();
}
// Fetch current department from DB.
// ConcurrencyToken may have changed.
var departmentToUpdate = await _context.Departments
.Include(i => i.Administrator)
.FirstOrDefaultAsync(m => m.DepartmentID == id);
if (departmentToUpdate == null)
{
return HandleDeletedDepartment();
}
// Set ConcurrencyToken to value read in OnGetAsync
_context.Entry(departmentToUpdate).Property(
d => d.ConcurrencyToken).OriginalValue = Department.ConcurrencyToken;
if (await TryUpdateModelAsync<Department>(
departmentToUpdate,
"Department",
s => s.Name, s => s.StartDate, s => s.Budget, s => s.InstructorID))
{
try
{
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
catch (DbUpdateConcurrencyException ex)
{
var exceptionEntry = ex.Entries.Single();
var clientValues = (Department)exceptionEntry.Entity;
var databaseEntry = exceptionEntry.GetDatabaseValues();
if (databaseEntry == null)
{
ModelState.AddModelError(string.Empty, "Unable to save. " +
"The department was deleted by another user.");
return Page();
}
var dbValues = (Department)databaseEntry.ToObject();
await SetDbErrorMessage(dbValues, clientValues, _context);
// Save the current ConcurrencyToken so next postback
// matches unless an new concurrency issue happens.
Department.ConcurrencyToken = (byte[])dbValues.ConcurrencyToken;
// Clear the model error for the next postback.
ModelState.Remove($"{nameof(Department)}.{nameof(Department.ConcurrencyToken)}");
}
}
InstructorNameSL = new SelectList(_context.Instructors,
"ID", "FullName", departmentToUpdate.InstructorID);
return Page();
}
private IActionResult HandleDeletedDepartment()
{
// ModelState contains the posted data because of the deletion error
// and overides the Department instance values when displaying Page().
ModelState.AddModelError(string.Empty,
"Unable to save. The department was deleted by another user.");
InstructorNameSL = new SelectList(_context.Instructors, "ID", "FullName", Department.InstructorID);
return Page();
}
private async Task SetDbErrorMessage(Department dbValues,
Department clientValues, SchoolContext context)
{
if (dbValues.Name != clientValues.Name)
{
ModelState.AddModelError("Department.Name",
$"Current value: {dbValues.Name}");
}
if (dbValues.Budget != clientValues.Budget)
{
ModelState.AddModelError("Department.Budget",
$"Current value: {dbValues.Budget:c}");
}
if (dbValues.StartDate != clientValues.StartDate)
{
ModelState.AddModelError("Department.StartDate",
$"Current value: {dbValues.StartDate:d}");
}
if (dbValues.InstructorID != clientValues.InstructorID)
{
Instructor dbInstructor = await _context.Instructors
.FindAsync(dbValues.InstructorID);
ModelState.AddModelError("Department.InstructorID",
$"Current value: {dbInstructor?.FullName}");
}
ModelState.AddModelError(string.Empty,
"The record you attempted to edit "
+ "was modified by another user after you. The "
+ "edit operation was canceled and the current values in the database "
+ "have been displayed. If you still want to edit this record, click "
+ "the Save button again.");
}
}
}
并发更新
OriginalValue在方法中OnGetAsync提取实体时,会使用ConcurrencyToken实体中的值进行更新。
EF Core生成包含SQL UPDATEWHERE原始ConcurrencyToken值的子句的命令。 如果 UPDATE 命令没有影响任何行,则会引发 DbUpdateConcurrencyException 异常。 当没有任何行具有原始的 ConcurrencyToken 值时,UPDATE 命令不会影响任何行。
public async Task<IActionResult> OnPostAsync(int id)
{
if (!ModelState.IsValid)
{
return Page();
}
// Fetch current department from DB.
// ConcurrencyToken may have changed.
var departmentToUpdate = await _context.Departments
.Include(i => i.Administrator)
.FirstOrDefaultAsync(m => m.DepartmentID == id);
if (departmentToUpdate == null)
{
return HandleDeletedDepartment();
}
// Set ConcurrencyToken to value read in OnGetAsync
_context.Entry(departmentToUpdate).Property(
d => d.ConcurrencyToken).OriginalValue = Department.ConcurrencyToken;
在前面高亮显示的代码中:
-
Department.ConcurrencyToken中的值是在针对Edit页面的Get请求中提取该实体时的值。 通过 Razor 页面中显示将要编辑的实体的隐藏字段将该值提供给OnPost方法。 模型绑定器将隐藏字段值复制到Department.ConcurrencyToken。 -
OriginalValueEF Core是子WHERE句中的用法。 在高亮显示的代码行执行之前:-
OriginalValue具有在此方法中调用FirstOrDefaultAsync时数据库中的值。 - 此值可能与编辑页面上显示的值不同。
-
- 突出显示的代码可确保 EF Core 使用所显示的
Department实体中的原始ConcurrencyToken值,并将其用于 SQLUPDATE语句的WHERE子句。
下面的代码展示了 Department 模型。
Department 在以下项中初始化:
-
通过 EF 查询的
OnGetAsync方法。 -
OnPostAsync页面中使用 模型绑定 的隐藏字段方法 Razor:
public class EditModel : PageModel
{
private readonly ContosoUniversity.Data.SchoolContext _context;
public EditModel(ContosoUniversity.Data.SchoolContext context)
{
_context = context;
}
[BindProperty]
public Department Department { get; set; }
// Replace ViewData["InstructorID"]
public SelectList InstructorNameSL { get; set; }
public async Task<IActionResult> OnGetAsync(int id)
{
Department = await _context.Departments
.Include(d => d.Administrator) // eager loading
.AsNoTracking() // tracking not required
.FirstOrDefaultAsync(m => m.DepartmentID == id);
if (Department == null)
{
return NotFound();
}
// Use strongly typed data rather than ViewData.
InstructorNameSL = new SelectList(_context.Instructors,
"ID", "FirstMidName");
return Page();
}
public async Task<IActionResult> OnPostAsync(int id)
{
if (!ModelState.IsValid)
{
return Page();
}
// Fetch current department from DB.
// ConcurrencyToken may have changed.
var departmentToUpdate = await _context.Departments
.Include(i => i.Administrator)
.FirstOrDefaultAsync(m => m.DepartmentID == id);
if (departmentToUpdate == null)
{
return HandleDeletedDepartment();
}
// Set ConcurrencyToken to value read in OnGetAsync
_context.Entry(departmentToUpdate).Property(
d => d.ConcurrencyToken).OriginalValue = Department.ConcurrencyToken;
前面的代码显示,来自 HTTP POST 请求的 Department 实体的 ConcurrencyToken 值被设置为来自 HTTP GET 请求的 ConcurrencyToken 值。
发生并发错误时,下面高亮显示的代码会获取客户端的值(提交到此方法的值)以及数据库中的值。
if (await TryUpdateModelAsync<Department>(
departmentToUpdate,
"Department",
s => s.Name, s => s.StartDate, s => s.Budget, s => s.InstructorID))
{
try
{
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
catch (DbUpdateConcurrencyException ex)
{
var exceptionEntry = ex.Entries.Single();
var clientValues = (Department)exceptionEntry.Entity;
var databaseEntry = exceptionEntry.GetDatabaseValues();
if (databaseEntry == null)
{
ModelState.AddModelError(string.Empty, "Unable to save. " +
"The department was deleted by another user.");
return Page();
}
var dbValues = (Department)databaseEntry.ToObject();
await SetDbErrorMessage(dbValues, clientValues, _context);
// Save the current ConcurrencyToken so next postback
// matches unless an new concurrency issue happens.
Department.ConcurrencyToken = dbValues.ConcurrencyToken;
// Clear the model error for the next postback.
ModelState.Remove($"{nameof(Department)}.{nameof(Department.ConcurrencyToken)}");
}
以下代码为每列添加自定义错误消息,这些列中的数据库值与提交到 OnPostAsync 的值不同:
private async Task SetDbErrorMessage(Department dbValues,
Department clientValues, SchoolContext context)
{
if (dbValues.Name != clientValues.Name)
{
ModelState.AddModelError("Department.Name",
$"Current value: {dbValues.Name}");
}
if (dbValues.Budget != clientValues.Budget)
{
ModelState.AddModelError("Department.Budget",
$"Current value: {dbValues.Budget:c}");
}
if (dbValues.StartDate != clientValues.StartDate)
{
ModelState.AddModelError("Department.StartDate",
$"Current value: {dbValues.StartDate:d}");
}
if (dbValues.InstructorID != clientValues.InstructorID)
{
Instructor dbInstructor = await _context.Instructors
.FindAsync(dbValues.InstructorID);
ModelState.AddModelError("Department.InstructorID",
$"Current value: {dbInstructor?.FullName}");
}
ModelState.AddModelError(string.Empty,
"The record you attempted to edit "
+ "was modified by another user after you. The "
+ "edit operation was canceled and the current values in the database "
+ "have been displayed. If you still want to edit this record, click "
+ "the Save button again.");
}
以下高亮显示的代码将 ConcurrencyToken 的值设置为从数据库获取的新值。 用户下次单击 Save 时,将只捕获自上次显示“编辑”页面以来发生的并发错误。
if (await TryUpdateModelAsync<Department>(
departmentToUpdate,
"Department",
s => s.Name, s => s.StartDate, s => s.Budget, s => s.InstructorID))
{
try
{
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
catch (DbUpdateConcurrencyException ex)
{
var exceptionEntry = ex.Entries.Single();
var clientValues = (Department)exceptionEntry.Entity;
var databaseEntry = exceptionEntry.GetDatabaseValues();
if (databaseEntry == null)
{
ModelState.AddModelError(string.Empty, "Unable to save. " +
"The department was deleted by another user.");
return Page();
}
var dbValues = (Department)databaseEntry.ToObject();
await SetDbErrorMessage(dbValues, clientValues, _context);
// Save the current ConcurrencyToken so next postback
// matches unless an new concurrency issue happens.
Department.ConcurrencyToken = dbValues.ConcurrencyToken;
// Clear the model error for the next postback.
ModelState.Remove($"{nameof(Department)}.{nameof(Department.ConcurrencyToken)}");
}
需要使用 ModelState.Remove 语句,因为 ModelState 具有先前的 ConcurrencyToken 值。 在 Razor 页面中,当两者同时存在时,字段的 ModelState 值优先于模型属性的值。
SQL Server 与 SQLite 代码差异
下面显示了 SQL Server 和 SQLite 版本之间的差异:
+ using System; // For GUID on SQLite
+ departmentToUpdate.ConcurrencyToken = Guid.NewGuid();
_context.Entry(departmentToUpdate)
.Property(d => d.ConcurrencyToken).OriginalValue = Department.ConcurrencyToken;
- Department.ConcurrencyToken = (byte[])dbValues.ConcurrencyToken;
+ Department.ConcurrencyToken = dbValues.ConcurrencyToken;
更新“编辑 Razor”页面
使用以下代码更新 Pages/Departments/Edit.cshtml:
@page "{id:int}"
@model ContosoUniversity.Pages.Departments.EditModel
@{
ViewData["Title"] = "Edit";
}
<h2>Edit</h2>
<h4>Department</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Department.DepartmentID" />
<input type="hidden" asp-for="Department.ConcurrencyToken" />
<div class="form-group">
<label>Version</label>
@Utility.GetLastChars(Model.Department.ConcurrencyToken)
</div>
<div class="form-group">
<label asp-for="Department.Name" class="control-label"></label>
<input asp-for="Department.Name" class="form-control" />
<span asp-validation-for="Department.Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Department.Budget" class="control-label"></label>
<input asp-for="Department.Budget" class="form-control" />
<span asp-validation-for="Department.Budget" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Department.StartDate" class="control-label"></label>
<input asp-for="Department.StartDate" class="form-control" />
<span asp-validation-for="Department.StartDate" class="text-danger">
</span>
</div>
<div class="form-group">
<label class="control-label">Instructor</label>
<select asp-for="Department.InstructorID" class="form-control"
asp-items="@Model.InstructorNameSL"></select>
<span asp-validation-for="Department.InstructorID" class="text-danger">
</span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-page="./Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
前面的代码:
- 将
page指令从@page更新为@page "{id:int}"。 - 新增隐藏行版本。
ConcurrencyToken必须添加,以便回发绑定该值。 - 显示
ConcurrencyToken的最后一个字节,用于调试。 - 将
ViewData替换为强类型InstructorNameSL。
使用编辑页测试并发冲突
在英语系打开编辑的两个浏览器实例:
- 运行该应用,然后选择“部门”。
- 右键单击英语系的“编辑”超链接,然后选择“在新选项卡中打开” 。
- 在第一个选项卡上,点击英语系的编辑超链接。
两个浏览器选项卡显示的信息相同。
在第一个浏览器选项卡中更改名称,然后单击“保存”。
浏览器显示更改值并更新 ConcurrencyToken 指示器后的索引页。 请注意更新后的 ConcurrencyToken 标记,它会显示在其他选项卡中的第二次 postback 时。
在第二个浏览器选项卡中更改另一个字段。
单击“ 保存”。 可看见所有不匹配数据库值的字段的错误消息:
此浏览器窗口并非有意更改名称字段。 将当前值(语言)复制并粘贴到名称字段。 退出选项卡。客户端验证将删除错误消息。
再次单击“保存”。 保存在第二个浏览器选项卡中输入的值。 在索引页中可以看到保存的值。
更新“删除”页面模型
使用以下代码更新 Pages/Departments/Delete.cshtml.cs:
using ContosoUniversity.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
namespace ContosoUniversity.Pages.Departments
{
public class DeleteModel : PageModel
{
private readonly ContosoUniversity.Data.SchoolContext _context;
public DeleteModel(ContosoUniversity.Data.SchoolContext context)
{
_context = context;
}
[BindProperty]
public Department Department { get; set; }
public string ConcurrencyErrorMessage { get; set; }
public async Task<IActionResult> OnGetAsync(int id, bool? concurrencyError)
{
Department = await _context.Departments
.Include(d => d.Administrator)
.AsNoTracking()
.FirstOrDefaultAsync(m => m.DepartmentID == id);
if (Department == null)
{
return NotFound();
}
if (concurrencyError.GetValueOrDefault())
{
ConcurrencyErrorMessage = "The record you attempted to delete "
+ "was modified by another user after you selected delete. "
+ "The delete operation was canceled and the current values in the "
+ "database have been displayed. If you still want to delete this "
+ "record, click the Delete button again.";
}
return Page();
}
public async Task<IActionResult> OnPostAsync(int id)
{
try
{
if (await _context.Departments.AnyAsync(
m => m.DepartmentID == id))
{
// Department.ConcurrencyToken value is from when the entity
// was fetched. If it doesn't match the DB, a
// DbUpdateConcurrencyException exception is thrown.
_context.Departments.Remove(Department);
await _context.SaveChangesAsync();
}
return RedirectToPage("./Index");
}
catch (DbUpdateConcurrencyException)
{
return RedirectToPage("./Delete",
new { concurrencyError = true, id = id });
}
}
}
}
删除页检测提取实体并更改时的并发冲突。
Department.ConcurrencyToken 是提取实体时的行版本。
EF Core 创建 SQL DELETE 命令时,它包括具有的 ConcurrencyToken 的 WHERE 子句。 如果 SQL DELETE 命令导致零行受影响:
-
SQL DELETE命令中的ConcurrencyToken与数据库中的ConcurrencyToken不匹配。 - 这将引发
DbUpdateConcurrencyException异常。 -
使用
concurrencyError调用OnGetAsync。
更新“删除 Razor”页面
使用以下代码更新 Pages/Departments/Delete.cshtml:
@page "{id:int}"
@model ContosoUniversity.Pages.Departments.DeleteModel
@{
ViewData["Title"] = "Delete";
}
<h1>Delete</h1>
<p class="text-danger">@Model.ConcurrencyErrorMessage</p>
<h3>Are you sure you want to delete this?</h3>
<div>
<h4>Department</h4>
<hr />
<dl class="row">
<dt class="col-sm-2">
@Html.DisplayNameFor(model => model.Department.Name)
</dt>
<dd class="col-sm-10">
@Html.DisplayFor(model => model.Department.Name)
</dd>
<dt class="col-sm-2">
@Html.DisplayNameFor(model => model.Department.Budget)
</dt>
<dd class="col-sm-10">
@Html.DisplayFor(model => model.Department.Budget)
</dd>
<dt class="col-sm-2">
@Html.DisplayNameFor(model => model.Department.StartDate)
</dt>
<dd class="col-sm-10">
@Html.DisplayFor(model => model.Department.StartDate)
</dd>
<dt class="col-sm-2">
@Html.DisplayNameFor(model => model.Department.ConcurrencyToken)
</dt>
<dd class="col-sm-10">
@Utility.GetLastChars(Model.Department.ConcurrencyToken)
</dd>
<dt class="col-sm-2">
@Html.DisplayNameFor(model => model.Department.Administrator)
</dt>
<dd class="col-sm-10">
@Html.DisplayFor(model => model.Department.Administrator.FullName)
</dd>
</dl>
<form method="post">
<input type="hidden" asp-for="Department.DepartmentID" />
<input type="hidden" asp-for="Department.ConcurrencyToken" />
<input type="submit" value="Delete" class="btn btn-danger" /> |
<a asp-page="./Index">Back to List</a>
</form>
</div>
上面的代码执行以下更改:
- 将
page指令从@page更新为@page "{id:int}"。 - 添加错误消息。
- 将“管理员”字段中的 FirstMidName 替换为 FullName。
- 更改
ConcurrencyToken以显示最后一个字节。 - 新增隐藏行版本。
ConcurrencyToken必须添加,以便回发绑定该值。
测试并发冲突
创建测试系。
在测试系打开删除的两个浏览器实例:
- 运行该应用,然后选择“部门”。
- 右键单击测试部门的“删除”超链接,然后选择“在新选项卡中打开”。
- 单击测试系的“编辑”超链接。
两个浏览器选项卡显示的信息相同。
在第一个浏览器选项卡中更改预算,然后点击保存。
浏览器显示更改值并更新 ConcurrencyToken 指示器后的索引页。 请注意更新后的 ConcurrencyToken 标记,它会显示在其他选项卡中的第二次 postback 时。
从第二个选项卡中删除测试部门。并发错误显示来自数据库的当前值。 单击“删除”删除实体,除非 ConcurrencyToken 已更新。
企业 Web 应用模式
有关创建可靠、安全、高性能、可测试且可缩放的 ASP.NET Core 应用的指导,请参阅 企业 Web 应用模式。 提供了一个具备完整生产质量的示例网页应用程序,该应用实现了这些模式。
相关内容
后续步骤
这是本系列的最后一个教程。 本教程系列的 MVC 版本还介绍了其他主题。