2

我真的很感激這方面的一些見解:下面的代碼關係字段是不是在編輯操作更新(ASP.NET,EF5)

 [HttpPost] 
    public ActionResult Edit(BeamCollection beamcollection) 
    { 
     if (ModelState.IsValid) 
     { 
      beamcollection.BeamMaterial = db.Types.Find(Convert.ToInt32(Request.Form.Get("BeamMaterial_ID"))); 
      db.Entry(beamcollection).State = EntityState.Modified; 
      db.SaveChanges(); 
      return RedirectToAction("Details", "Bridge"); 
     } 
     return View(beamcollection); 
    } 

當我試圖修改BeamCollection記錄,所有的改變都體現並保存到數據庫,除了beamcollection.BeamMaterial從DropDownList中獲取所選值。當我調試時,我可以看到選定的值正被分配到beamcollection.BeamMaterial!

順便說一句,這個字段定義如下

public virtual AllTypes BeamMaterial { get; set; } 

所以它反映了一個與AllTypes一對多的關係,但它是一個單向的關係。

是什麼樣的怪(對我來說),是用於創建動作相同的技術,它完美的作品:

public ActionResult Create(BeamCollection beamcollection) 
    { 
     if (ModelState.IsValid) 
     { 
      beamcollection.BridgeInfo = db.Bridges.Find(bridgeID); 
      beamcollection.BeamMaterial = db.Types.Find(Convert.ToInt32(Request.Form.Get("BeamMaterial_ID"))); 
      db.BeamCollections.Add(beamcollection); 
      db.SaveChanges(); 
      return RedirectToAction("Details", "Bridge"); 
     } 
     return View(beamcollection); 
    } 

爲什麼會出現這種情況,如何使其工作,請幫助。

回答

0

由於法布里斯的提示,我設法找到正確的方法,下面是代碼:

  var currentBeamCollection = db.BeamCollections.Find(beamcollection.ID); 
      db.Entry(currentBeamCollection).CurrentValues.SetValues(beamcollection); 
      currentBeamCollection.BeamMaterial = beamcollection.BeamMaterial; 
      db.SaveChanges(); 

的邏輯如下:獲得原始紀錄,更新所有字段(導航屬性除外,下面閱讀),更新導航屬性,最後保存。

當我試着做以下

db.Entry(currentBeamCollection).CurrentValues.SetValues(beamcollection.BeamMaterial); 

系統無法與抱怨設置ID屬性異常。我還讀到CurrentValues.SetValues()不更新導航屬性,我注意到BeamMaterial屬性沒有被更新,所以我需要手動更新它。

謝謝Fabrice。

0

嘗試使用:

db.attach(beamcollection.GetType().Name,beamcollection); 
db.ObjectStateManager.ChangeObjectState(beamcollection, EntityState.Modified); 
db.SaveChanges(); 
+0

謝謝面料,我認爲你的建議適用於EF4但不適用EF5。我檢查了這個[http://stackoverflow.com/questions/7113434/where-is-context-entry]提到了這些差異。我想我想說的是我現在的代碼完成了你的建議。 – user1773630 2013-04-09 12:15:17

+0

看看這篇文章:http://stackoverflow.com/questions/13931714/mvc-4-ef-5-savechanges-does-not-update-database。 – 2013-04-09 19:54:32

相關問題