MVC one to zero inserting not updating
I am using EntityFramework. I have an "Application" object (which has a field certificateReasonID) which can have one or zero CertificateReasons - so there is a ralationship to the "CertificateReason" table, and visiually on the edmx diagram we do not see the certificateReaso开发者_高级运维nTypeID field.
When I update an Application - it INSERTS a new CertificateReason and UPDATES Application.certificateReasonTypeID to the new ID - instead of updatig Application.certificateReasonTypeID to the selected ID.
The CertificateReason object is in an added state(technically correct). The aspx code is
<%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>
<%}%>
The update code is
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();
}
}
Thanks
answer was to pass the Application model into the Edit post - had to put a hidden field on form for the object to be filled correctly) and ensure I was getting the Application objetc not a var. Can't use the ModelState.IsValid as always false, but correctly updates not inserts. Other point was had to do an .Include("CertificateReasons") on the get.
public ActionResult Edit(Application app, FormCollection collection) {
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);
}
精彩评论