2011-11-16 31 views
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 }); 
} 

第一個是通過有沒有問題,但是,當它試圖更新第二個,併發在扭結並引發以下錯誤:

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

這裏是_accommpropertyseasondetailrepoEdit方法:

public void Edit(AccommPropertySeasonDetail entity) { 

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

這裏是_accommpropertyseasonrepoEdit方法:

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) 

問題現在解決了!

+0

如果您在'_accommpropertyseasondetailrepo.Edit'方法中設置了斷點,並且如果您嘗試在斷點之前選擇'AccommPropertySeasonDetail'記錄,記錄是否會加載? – counsellorben

+0

@counsellorben yep! ModelBinder完美地綁定到該對象。 – tugberk

+0

您想要更新單個事務中的兩個實體,並在發生故障時回滾這些更改?沒有看到你的存儲庫方法,你不知道你要做什麼。 – Dismissile

回答

1

複製/從我的評論貼在OP

這看起來並不像它有什麼併發。出於某種原因,正在編寫SQL Update語句的方式,實體框架期望項目被更新,並且這些項目不在那裏。有沒有可能嘗試在LINQPad中運行相同的代碼並觀察SQL結果以查看發生了什麼?

2

可能有一個完美的理由,你這樣做,但不知道原因這看起來像一個非常糟糕的方式來完成你在做什麼。

您應該查詢數據庫以確保實體存在,然後如果存在,您應該更新實體並保存這些更改。

var entity = repository.GetAccomPropertySeason(id); 

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

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

你寫這個的方式,如果該對象實際上不存在,那麼你將得到這個錯誤。

您確定您的Details對象具有正確的父ID嗎?它是否正確綁定?從外觀上看,您告訴上下文它存在並且您將更新它,但上下文實際上在調用SaveChanges時找不到該實體。

如果意圖是要創建一個新的對象(而不是修改現有的對象),那麼你應該設置狀態爲增加,而不是。

+0

我很欣賞這種努力,但我解決了這個問題。看到我更新的問題。粗心的錯誤!謝謝! – tugberk