更新現有記錄時的實體框架核心錯誤

asp.net-core asp.net-mvc-scaffolding entity-framework-core 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發布帖子之後,我在上面的Action方法中嘗試了以下內容。它不會給我一個錯誤,但也不會更新數據庫:

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


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow