【发布时间】:2016-12-20 12:45:11
【问题描述】:
在我的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中对应的表Weeks有WeekId as an identity column and as the PK。而且,该表只包含一条记录。
更新:
按照这个Post from user sstan,我在上面的Action Method中尝试了以下。它不会给我一个错误,但也不会更新数据库:
WeekModel oWeekModel = new WeekModel();
_context.WeekModel.Attach(oWeekModel);
oWeekModel.DayOfWeek= iWeekDay;
await _context.SaveChangesAsync();
【问题讨论】:
-
为什么要创建新实体进行更新?
-
您需要在将新创建的模型传递给更新方法之前附加它。或者先做一个查询去获取,否则不被追踪
标签: visual-studio-2015 asp.net-core entity-framework-core asp.net-mvc-scaffolding