Entity Framework 更新现有记录时出现核心错误

Entity Framework Core error on updating an existing record

在我的 ASP.NET-Core Code First project 中,我在以下 Action Method 中的 SaveChangesAsync() 上收到以下错误:

错误

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; }
}

注意:SQLServer 2014 Db中对应的tableWeeksWeekId as an identity column and as the PK。而且,table只包含一条记录。

更新:

在这个 之后,我在上面的操作方法中尝试了以下操作。它没有给我一个错误,但也没有更新数据库:

WeekModel oWeekModel = new WeekModel();
_context.WeekModel.Attach(oWeekModel);
oWeekModel.DayOfWeek= iWeekDay;
await _context.SaveChangesAsync();

根据 @Tseng@ademcaglin 的建议,我能够按如下方式解决问题。 注意:感谢上述用户(感谢这些用户):

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();
   }
}