ASP.NET MVC: UpdateModel failing when attempting to save changes to collection - creating new objects instead of updating
I'm in a bit of a pickle.
Basically, I am trying to create an edit for for a collection of objects - EF objects to be precise. I pass my view a viewmodel that contains an object of type Call. This is an EF type. A Call has many Answers. In the view I loop over the Answers and output a form:
@using (Html.BeginForm())
{
foreach(var a in Model.Answers)
{
Html.RenderPartial("_AnswerForm", a);
}
<input type="submit" value="Save Answers" />
}
The partial view is as follows:
@using (Html.BeginCollectionItem("Answers"))
{
<div data-role="fieldcontain">
@Html.HiddenFor(z => z.QuestionID)
@Html.HiddenFor(z => z.CallID)
@Html.LabelFor(x => x.OnEntryAnswer)
@Html.CheckBoxFor(x => x.OnEntryAnswer)
@Html.ValidationMessageFor(x => x.OnEntryAnswer)
@Html.LabelFor(x => x.OnExitValue)
@Html.TextBoxFor(x => x.OnExitValue)
@Html.ValidationMessageFor(x => x.OnExitValue)
@Html.HiddenFor(x => x.id)
</div>
}
My controller action looks something like....
[HttpPost]
public ActionResult FacingsAdjacency(FormCollection data)
{
Call activeCall = null;
try { activeCall = this.GetCallInformation(); }
catch (NoActiveCallException ex) { TempData["message"] = "No Call In Progress!"; RedirectToAction("NoCallInProgress"); }
开发者_如何转开发 QuestionFormViewModel vm = new QuestionFormViewModel(activeCall, "FacingsAdjacency");
UpdateModel(activeCall.CallAnswers, "Answers");
callRepository.Save();
return View(vm);
}
When Save is called (which calls savechanged on the context) an error is thrown:
The relationship could not be changed because one or more of the foreign-key properties is non-nullable
If I inspect the items the datacontext is tracking I see there are twice as many as there should be. There are three to be modfied (correct) and three with exactly the same details, flagged as added. All the data is coming through from the POST to populate the EF objects - I'm just not sure why its failing.
Thanks
I've found that EF can be a bit of a pain when managing object references and saving them back to the database.
I suggest you 'scrub' the Answers before the call to callRepository.Save() to remove the referenced objects (just set the properties to null), just keeping the ID fields.
Well this is weird. If someone can explain this I would love to hear it!
Basically I solved the issue by removing the auto incrementing primary key from my answers table and using a composite key instead. Inspired by this post: Updating a list of foreign keys in EF4, using MVC 2 Repository Viewmodel Pattern
I have no idea why using a single primary key instead of a composite would mess things up.
In your repository in update method try
_dbSet.Attach(entity);
_dbContext.Entry(entity).State = System.Data.EntityState.Modified;
_dbContext.SaveChanges();
精彩评论