在我的ASP.NET MVC應用程序,我試圖更新兩個相關型號如下:更新兩個相關的模型和併發性的實體框架
if (ModelState.IsValid) {
_accommpropertyseasonrepo.Edit(accommPropertySeasonCreateViewModel.AccommPropertySeason);
_accommpropertyseasonrepo.Save();
_accommpropertyseasondetailrepo.Edit(accommPropertySeasonCreateViewModel.AccommPropertySeasonDetail);
_accommpropertyseasondetailrepo.Save();
return RedirectToAction("Details", new { id = id });
}
第一個是通過有沒有問題,但是,當它試圖更新第二個,併發在扭結並引發以下錯誤:
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries
什麼是實現什麼,我想在這裏做的呢?
UPDATE
這裏是_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;
}
UPDATE 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);
}
UPDATE
殘酷的事實:我忘了下面的代碼行上我的看法,因此模型回來了沒有PK:
@Html.HiddenFor(m => m.AccommPropertySeasonDetail.AccommPropertySeasonDetailID)
問題現在解決了!
如果您在'_accommpropertyseasondetailrepo.Edit'方法中設置了斷點,並且如果您嘗試在斷點之前選擇'AccommPropertySeasonDetail'記錄,記錄是否會加載? – counsellorben
@counsellorben yep! ModelBinder完美地綁定到該對象。 – tugberk
您想要更新單個事務中的兩個實體,並在發生故障時回滾這些更改?沒有看到你的存儲庫方法,你不知道你要做什麼。 – Dismissile