更新现有记录时的实体框架核心错误

时间:2016-08-13 18:57:50

标签: visual-studio-2015 asp.net-core entity-framework-core asp.net-mvc-scaffolding

在我的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中的相应表WeeksWeekId 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();

1 个答案:

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