Entity Framework Core 2,向模型添加了并发 token 属性
[Timestamp]
public byte[] Timestamp { get; set; }
Controller 编辑失败
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Guid id, [Bind("Id,Name,Description,IsDeleted,ParentId")] ItemStatus itemStatus)
{
if (id != itemStatus.Id)
return NotFound();
if (ModelState.IsValid)
{
try
{
_context.Update(itemStatus);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ItemStatusExists(itemStatus.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["ParentId"] = new SelectList(_context.ItemStatus, "Id", "Description", itemStatus.ParentId);
return View(itemStatus);
}
发生 SaveChangesAsync 时,会出现我收到的特定错误。接住POP,当我介入时,它会直接 throw 。
DbUpdateConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.
Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ThrowAggregateUpdateConcurrencyException(int commandIndex, int expectedRowsAffected, int rowsAffected)
搜索错误消息没有帮助。确实找到了这篇文章,但似乎没有帮助。
https://learn.microsoft.com/en-us/ef/core/saving/concurrency
最佳答案
如评论中所示,我缺少一个隐藏字段来“保存” View 中的时间戳。
按照这个例子:https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/concurrency
为了清楚起见,添加了我修改过的编辑。我也必须做类似删除的事情。这需要添加到编辑 View <input type="hidden" asp-for="Timestamp" />
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Guid id, [Bind("Id,Name,Description,ParentId,Timestamp")] ItemStatus itemStatus)
{
if (id != itemStatus.Id)
return NotFound();
if (ModelState.IsValid)
{
try
{
_context.Update(itemStatus);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ItemStatusExists(itemStatus.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["ParentId"] = new SelectList(_context.ItemStatus, "Id", "Description", itemStatus.ParentId);
return View(itemStatus);
}
关于c# - ASP.Net & EF Core 2 和并发 token 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46246871/