在我ASP.NET-Core Code First project
實體框架核心錯誤,我發現了以下錯誤上SaveChangesAsync()
在以下Action Method
:上更新現有記錄
錯誤
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
操作方法:
public async Task<IActionResult> UpdateWeekDay(int iWeekDay)
{
if (ModelState.IsValid)
{
WeekModel oWeekModel = new WeekModel();
oWeekModel.DayOfWeek= iWeekDay;
_context.Update(oWeekModel);
await _context.SaveChangesAsync();
return View();
}
}
型號:
public class WeekModel
{
[Key]
public int WeekId { get; set; }
public int DayOfWeek { get; set; }
}
注意:在SQL Server 2014塊都有WeekId as an identity column and as the PK
在相應的表格Weeks
。而且,該表只包含一條記錄。
UPDATE:
在此之後Post from user sstan,我試圖在上面操作方法如下。它沒有給我一個錯誤,但沒有更新的數據庫,以及:
WeekModel oWeekModel = new WeekModel();
_context.WeekModel.Attach(oWeekModel);
oWeekModel.DayOfWeek= iWeekDay;
await _context.SaveChangesAsync();
爲什麼要創建新的更新實體? –
在將它傳遞給更新方法之前,您需要附加新創建的模型。或者先執行一個查詢來獲取它,否則不會跟蹤 – Tseng