Nel mio ASP.NET-Core Code First project
, sto ricevendo il seguente errore su SaveChangesAsync()
nel seguente Action Method
:
Errore
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
Metodo di azione :
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();
}
}
Modello :
public class WeekModel
{
[Key]
public int WeekId { get; set; }
public int DayOfWeek { get; set; }
}
Nota : la tabella corrispondente Weeks
in SQL Server 2014 Db ha WeekId as an identity column and as the PK
. Inoltre, la tabella contiene solo un record.
AGGIORNAMENTO :
Seguendo questo post da utente sstan , ho provato quanto segue nel metodo di azione sopra. Non mi dà un errore ma non aggiorna anche il db:
WeekModel oWeekModel = new WeekModel();
_context.WeekModel.Attach(oWeekModel);
oWeekModel.DayOfWeek= iWeekDay;
await _context.SaveChangesAsync();
Seguendo i consigli di @Tseng
e @ademcaglin
e questo post di @sstan
sono riuscito a risolvere il problema come segue. NOTA : il credito va agli utenti sopra citati (i miei ringraziamenti a questi utenti):
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();
}
}