gpt4 book ai didi

c# - ASP.Net & EF Core 2 和并发 token 错误

转载 作者:行者123 更新时间:2023-11-30 23:08:53 25 4
gpt4 key购买 nike

Entity Framework Core 2,为模型添加了并发标记属性

[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 发生时。捕获流行音乐,当我介入时,它会直接 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com