2

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();
Community
  • 1
  • 1
nam
  • 21,967
  • 37
  • 158
  • 332

1 Answers1

0

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();
   }
}
Community
  • 1
  • 1
nam
  • 21,967
  • 37
  • 158
  • 332
  • You don't need to attach fetched entity. You can remove `_context.WeekModel.Attach(oWeekModel)`. – adem caglin Aug 14 '16 at 11:41
  • @ademcaglin Per your suggestion, I removed the attach fetched entity and it still works. Could you please explain why attach fetched entity was not necessary here and when it will be necessary? – nam Aug 14 '16 at 16:12
  • You don't need because you didn't create new entity, you fetched it from database via `DbContext`. Example in your question need to attach(as @Tseng said) because you created new entity(not fetched). Also see https://msdn.microsoft.com/en-us/data/jj592676.aspx – adem caglin Aug 15 '16 at 06:04