If I have 2 tables in my database: Foo and bar. Foo is identified by FooId and Bar is identifier by BarId. A Bar can have 0 to many Foos therefore Foo has BarId as a foreign key.
I have a model which represents this and an view which can be used to edit a Foo and select (from a dropdown) the associated Bar.
Given the following method on the controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection formCollection)
{
Foo originalFoo = FooById(id);
if (!ModelState.IsValid)
{
return View(new VenueViewModel(originalVenue, _db.GetCounties(), _db.VenueTypeSet));
}
UpdateModel(originalFoo);
/* Instead of using UpdateModel I could just iterate through
formCollection and manually update originalFoo, it would
work but surely there is a better way? */
_db.SaveChanges();
return RedirectToAction("Index");
}
The call to UpdateModel throws an InvalidOperationException with no InnerException:
The model of type 'TestApplication.Models.Foo' was not successfully updated.
What's the correct way for my controller to update my Entity Framework-based Model from the drop down in my view?