visual studio 2015 -实体框架核心在更新现有记录时出错



在我的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; }
}

说明: SQL Server 2014 Db中对应的表WeeksWeekId as an identity column and as the PK。而且,该表只包含一条记录。

:

在sstan用户的这篇文章之后,我尝试了下面的动作方法。它没有给我一个错误,但也不更新数据库:

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

根据@Tseng@ademcaglin的建议以及@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();
   }
}

最新更新