【问题标题】:Entity Framework Core error on updating an existing record更新现有记录时出现 Entity Framework Core 错误
【发布时间】: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中对应的表WeeksWeekId 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


【解决方案1】:

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

【讨论】:

  • 您不需要附加获取的实体。你可以删除_context.WeekModel.Attach(oWeekModel)
  • @ademcaglin 根据您的建议,我删除了附加获取的实体,它仍然有效。您能否解释一下为什么这里不需要附加获取的实体以及何时需要?
  • 您不需要,因为您没有创建新实体,而是通过 DbContext 从数据库中获取它。您问题中的示例需要附加(如@Tseng 所说),因为您创建了新实体(未获取)。另见msdn.microsoft.com/en-us/data/jj592676.aspx
猜你喜欢
  • 2020-12-06
  • 2017-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-21
  • 2013-02-26
  • 1970-01-01
相关资源
最近更新 更多