2

我真的很感激对此的一些见解:以下代码

        [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 记录时,所有更改都会反映并保存到数据库中,除了从 DropDownList 获取所选值的 beamcollection.BeamMaterial。当我调试时,我可以看到选定的值被分配给了 beamcollection.BeamMaterial!

顺便说一下,这个字段定义如下

public virtual AllTypes BeamMaterial { get; set; }

所以它反映了与AllTypes的一对多关系,但它是一种单向关系。

有什么奇怪的(对我来说),是相同的技术被用于 Create 动作,它完美地工作:

    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);
    }

为什么会发生这种情况以及如何使其工作,请帮助。

4

2 回答 2

0

尝试使用:

db.attach(beamcollection.GetType().Name,beamcollection);
db.ObjectStateManager.ChangeObjectState(beamcollection, EntityState.Modified);
db.SaveChanges();
于 2013-04-09T10:54:09.270 回答
0

感谢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 属性没有更新,所以我需要手动更新它。

谢谢法布里斯。

于 2013-04-10T06:37:16.430 回答