In my mvc application I have a lot of related data, I need to write a method to allow the edit/update of that related data, at the moment my data is handled using a ViewModel. I have attempted to write a method to do this but I can't get it to work correctly and I'm not sure my approach is quite right and so I wanted to get some guidance.
Here is my code:
Controller Code
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(FullVesselViewModel model)
{
var vessel = new tbl_vessels
{
vessel_idx = model.vessel_idx,
vessel_name = model.vessel_name
};
var vessel_spec = new tbl_vessel_spec
{
spec_idx = model.spec_idx,
bhp = model.bhp
}
using (var context = new dataEntities())
{
context.Entry(vessel).State = EntityState.Modified;
context.Entry(vessel_spec).State = EntityState.Modified;
context.SaveChanges();
return RedirectToAction("Index");
}
}
My initial though was to declare my viewmodel and then break down the two related entities and store them in variables, comitting those variables as modified and then saving my changes. My above approach returns concurrency errors. I have stored the indexes of the entities in a couple of hidden for fields to see if that would help but I've had no luck.
View
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.vessel_idx)
@Html.HiddenFor(model => model.spec_idx)
...input fields etc ...
}
Is my thinking correct for this sort of scenario or have I over engineered something that can be done simpler?
The error that I get is as follows and is triggered at SaveChanges():
Entity Framework: “Store update, insert, or delete statement affected an unexpected number of rows (0).”