在我的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 Db中的相应表Weeks
为WeekId as an identity column and as the PK
。此外,该表仅包含一条记录。
更新:
在Post from user sstan之后,我在上面的Action Method中尝试了以下内容。它不会给我一个错误,但也不会更新数据库:
WeekModel oWeekModel = new WeekModel();
_context.WeekModel.Attach(oWeekModel);
oWeekModel.DayOfWeek= iWeekDay;
await _context.SaveChangesAsync();
答案 0 :(得分:0)
根据@Tseng
和@ademcaglin
以及this post from @sstan
的建议,我能够解决以下问题。 注意:信用证转到上述用户(感谢这些用户):
public async Task<IActionResult> UpdateWeekDay(int iWeekDay)
{
if (ModelState.IsValid)
{
WeekModel oWeekModel = _context.WeekModel.Where(s => s.DayOfWeek > 0).FirstOrDefault<CurrentYear>();
_context.WeekModel.Attach(oWeekModel);
oWeekModel.DayOfWeek= iWeekDay;
await _context.SaveChangesAsync();
return View();
}
}