我正在使用 EF Core 5.0 Version
Asp.net core razor page (.Net 5.0) SQL 2019
學生表包含 RowVersion(TimeStamp not null) 我生成了 dbcontext 腳手架,模型構建器是
entity.Property(e => e.RowVersion)
.IsRequired()
.IsRowVersion()
.IsConcurrencyToken();
每當我更新學生姓名時,我都會收到錯誤訊息
DbUpdateConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0 row(s).
我嘗試用
entity.Property(e => e.RowVersion)
.IsRowVersion()
進行更新的代碼:
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
_context.Attach(Student).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync(true);
}
catch (DbUpdateConcurrencyException)
{
if (!StudentExists(Student.StudentId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToPage("./Index");
}
但我無法克服錯誤。問題僅在于 sql-server 的 TimeStamp 資料型別。
uj5u.com熱心網友回復:
8 小時后,我發現更新命令本身缺少 RowVersion,因為它沒有在回發中傳遞。
我在視圖頁面中包含了一個隱藏欄位,用于解決問題的 Rowversion。
<input type="hidden" asp-for="Student.StudentId" />
<input type="hidden" asp-for="Student.RowVersion" />
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/444905.html
