0

在我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塊都有WeekId as an identity column and as the PK在相應的表格Weeks。而且,該表只包含一條記錄。

UPDATE

在此之後Post from user sstan,我試圖在上面操作方法如下。它沒有給我一個錯誤,但沒有更新的數據庫,以及:

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

爲什麼要創建新的更新實體? –

+1

在將它傳遞給更新方法之前,您需要附加新創建的模型。或者先執行一個查詢來獲取它,否則不會跟蹤 – Tseng

回答

0

在從@Tseng@ademcaglinthis 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(); 
    } 
} 
+0

您不需要附加獲取的實體。你可以刪除'_context.WeekModel.Attach(oWeekModel)'。 –

+0

@ademcaglin根據你的建議,我刪除了附加獲取的實體,它仍然有效。你能否解釋爲什麼在這裏附加獲取的實體不是必要的,何時需要? – nam

+0

你不需要,因爲你沒有創建新的實體,你通過'DbContext'從數據庫中獲取它。您的問題中的示例需要附加(如@Tseng所述),因爲您創建了新實體(未提取)。另請參閱https://msdn.microsoft.com/en-us/data/jj592676.aspx –