【问题标题】:Relationship field is not updated in Edit action (ASP.NET, EF5)关系字段未在编辑操作中更新(ASP.NET、EF5)
【发布时间】:2013-04-10 14:37:16
【问题描述】:

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

        [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的一对多关系,但它是单向关系。

有点奇怪(对我来说),创建动作使用了相同的技术,而且效果很好:

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

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

【问题讨论】:

    标签: asp.net-mvc entity-framework entity-framework-5 html-select


    【解决方案1】:

    尝试使用:

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

    【讨论】:

    【解决方案2】:

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

    谢谢法布里斯。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多