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

相关问题