Asp.net mvc 编辑操作(ASP.NET,EF5)中未更新关系字段

Asp.net mvc 编辑操作(ASP.NET,EF5)中未更新关系字段,asp.net-mvc,entity-framework,entity-framework-5,html-select,Asp.net Mvc,Entity Framework,Entity Framework 5,Html Select,我真的很想了解一下:下面的代码 [HttpPost] public ActionResult Edit(BeamCollection beamcollection) { if (ModelState.IsValid) { beamcollection.BeamMaterial = db.Types.Find(Convert.ToInt32(Request.Form.Get("BeamMaterial_ID")

我真的很想了解一下:下面的代码

        [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记录时,所有更改都会反映并保存到DB中,BeamCollection.BeamMaterial除外,它从DropDownList中获取所选值。调试时,我可以看到所选的值正在分配给beamcollection.BeamMaterial

顺便说一下,该字段的定义如下

public virtual AllTypes BeamMaterial { get; set; }
因此,它反映了与所有类型的一对多关系,但它是单向关系

(对我来说)有点奇怪的是,相同的技术被用于创建动作,而且效果非常好:

    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);
    }
为什么会发生这种情况以及如何使其工作,请帮助。

尝试使用:

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

多亏了Fabrice的提示,我找到了正确的方法,下面是代码:

            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。

谢谢Fabric,我认为你的建议对EF4有效,但对EF5无效。我检查了这个[它提到了这些差异。我想我想说的是,我当前的代码符合你的建议。请看这篇文章:。