Search code examples
visual-studio-2015asp.net-coreentity-framework-coreasp.net-mvc-scaffolding

Entity Framework Core error on updating an existing record


In my ASP.NET-Core Code First project, I'm getting the following error on SaveChangesAsync() in the following Action Method:

Error

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

Action Method:

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

Model:

public class WeekModel
{
    [Key]
    public int WeekId { get; set; }
    public int DayOfWeek { get; set; }
}

NOTE: The corresponding table Weeks in the SQL Server 2014 Db has WeekId as an identity column and as the PK. Moreover, the table contains only one record.

UPDATE:

Following this Post from user sstan, I tried the following in the above Action Method. It does not give me an error but does not update the db as well:

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

Solution

  • Following advice from @Tseng and @ademcaglin and this post from @sstan I was able to resolve the issue as follows. NOTE: Credit goes to above mentioned users (my thanks to these users):

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