MVC一到零插入不更新

时间:2010-01-07 20:52:23

标签: asp.net-mvc entity-framework insert-update

我正在使用EntityFramework。我有一个“应用程序”对象(有一个字段certificateReasonID),它可以有一个或零个CertificateReasons - 因此与“CertificateReason”表存在关系,并且在edmx图上看起来我们没有看到certificateReasonTypeID字段。

当我更新应用程序时 - 它会将新的CertificateReason和UPDATES Application.certificateReasonTypeID枚举到新ID中 - 而不是将Application.certificateReasonTypeID更新为所选ID。

CertificateReason对象处于添加状态(技术上正确)。 aspx代码是

<%foreach (var certReason in Model.CertificateReasons)                  
                  { %>
                        <li>
                        <%= Html.RadioButton("CertificateReason.id", certReason.id)%>
                        <!-- only because it is adding when it shouldn't -we have to set the other non null values(i.e. not id) in the object else it will fail when it tries to save-->
                          <input type="hidden" value="<%= certReason.meaning %>" name="CertificateReason.meaning"/>
                            <input type="hidden" value="<%= certReason.effectiveFrom %>" name="CertificateReason.effectiveFrom"/>
                            <input type="hidden" value="<%= certReason.createdWhen %>" name="CertificateReason.createdWhen"/>
                        <label for="certificateReasonTypeID<%=certReason.meaning%>"><%=certReason.meaning%></label>
                        </li>
                <%}%>

更新代码为

 public ActionResult Edit(int id, FormCollection collection, ApplicationViewModel model)
 {
     var appToUpdate = OMF.Application.First(m => m.id == id);
     UpdateModel(movieToUpdate, collection.ToValueProvider()); 
     if (ModelState.IsValid)
     {

          OMF.ApplyPropertyChanges(movieToUpdate.EntityKey.EntitySetName, appToUpdate );
          OMF.SaveChanges();
      }
}

由于

1 个答案:

答案 0 :(得分:0)

回答是将应用程序模型传递到编辑帖子 - 必须在表单上放置一个隐藏字段以便正确填充对象)并确保我获得的应用程序对象不是var。不能将ModelState.IsValid一直使用为false,但正确更新不会插入。其他一点是必须在get上执行.Include(“CertificateReasons”)。

public ActionResult Edit(应用程序app,FormCollection集合)         {

        Application movieToEdit = OMF.GetApplication(app.id);           
        if(app.CertificateReason != null)
            movieToEdit.CertificateReason = OMF.CertificateReason.First(d => d.id == app.CertificateReason.id);
        TryUpdateModel(movieToEdit);

        //if (ModelState.IsValid) --can't use this
       // {
            OMF.SaveChanges();
       // }
        return RedirectToAction("Edit", app.id);

    }