0

在我的 ASP.NET MVC 应用程序上,我正在尝试更新两个相关模型,如下所示:

if (ModelState.IsValid) {

    _accommpropertyseasonrepo.Edit(accommPropertySeasonCreateViewModel.AccommPropertySeason);
    _accommpropertyseasonrepo.Save();

    _accommpropertyseasondetailrepo.Edit(accommPropertySeasonCreateViewModel.AccommPropertySeasonDetail);
    _accommpropertyseasondetailrepo.Save();

    return RedirectToAction("Details", new { id = id });
}

第一个通过没有问题,但是当它尝试更新第二个时,并发正在扭结并引发以下错误:

存储更新、插入或删除语句影响了意外数量的行 (0)。自加载实体后,实体可能已被修改或删除。刷新 ObjectStateManager 条目

实现我在这里尝试做的事情的方法是什么?

更新

这是_accommpropertyseasondetailrepo Edit方法:

public void Edit(AccommPropertySeasonDetail entity) {

    _context.Entry(entity).State = System.Data.EntityState.Modified;
}

这是_accommpropertyseasonrepo Edit方法:

public void Edit(AccommPropertySeason entity) {
            _context.Entry(entity).State = System.Data.EntityState.Modified;
        }

更新 2

这是整个动作方法:

public ActionResult SeasonEdit_post(int id, int subid, 
    [Bind(Exclude = 
        "AccommPropertySeason.CreatedBy,AccommPropertySeason.CreatedOn")]
    AccommPropertySeasonCreateViewModel accommPropertySeasonCreateViewModel) {

    if (ModelState.IsValid) {

        _accommpropertyseasonrepo.Edit(accommPropertySeasonCreateViewModel.AccommPropertySeason);
        _accommpropertyseasonrepo.Save();


                    _accommpropertyseasondetailrepo.Edit(accommPropertySeasonCreateViewModel.AccommPropertySeasonDetail);
        _accommpropertyseasondetailrepo.Save();

        return RedirectToAction("Details", new { id = id });
    }

    return View(accommPropertySeasonCreateViewModel);
}

更新

残酷的真相:我在视图中忘记了以下代码行,因此模型在没有 PK 的情况下返回:

@Html.HiddenFor(m => m.AccommPropertySeasonDetail.AccommPropertySeasonDetailID)

现在问题解决了!

4

2 回答 2

2

您这样做可能有一个非常好的理由,但是在不知道这个原因的情况下,这看起来是完成您正在做的事情的一种非常糟糕的方式。

您应该查询数据库以确保实体存在,然后如果存在,您应该更新实体并保存这些更改。

var entity = repository.GetAccomPropertySeason(id);

if( entity == null )
   return View("NotFound");

// update the model here
repository.SaveChanges();

你写这个的方式,如果对象实际上不存在,那么你会得到这个错误。

您确定您的 Details 对象具有正确的父 ID 吗?是否正确绑定?从外观上看,您是在告诉上下文它存在并且您将对其进行更新,但是当上下文调用 SaveChanges 时,实际上无法找到该实体。

如果意图是创建一个新对象(而不是修改现有对象),那么您应该将状态设置为已添加。

于 2011-11-16T21:14:42.747 回答
1

从我对 OP 的评论中复制/粘贴

这看起来与并发无关。由于某种原因,编写 SQL 更新语句的方式,实体框架期望更新项目,而这些项目不存在。您是否有机会尝试在 LINQPad 中运行相同的代码并观察 SQL 结果以了解发生了什么?

于 2011-11-16T23:31:22.790 回答