I've looked around for hours, but I can't seem to find a straight forward method for solving my problem.
Basically, I have a 1-to-many relationship, bridged with a table. My controller seems to handle the 'create' method perfectly, creating records within the '1' table and the bridging 'many' table.
However, the 'edit' method doesn't seem to modify/update the bridging table at all. Any thoughts on what I'm doing wrong, and why it differs from the 'create' approach?
For brevity, let's say I have the following model:
public class Incident
{
[Key]
public int IncidentID { get; set; }
public string Title { get; set; }
public virtual ICollection<IncidentResources> Resources{ get; set; }
}
And an Resource model:
public class Resource
{
[Key]
public int ResourceID{ get; set; }
public int Name { get; set; }
...OTHER FIELDS REMOVED FOR BREVITY...
}
And I am bridging these two via a bridging table and model:
public class IncidentResource
{
[Key]
public int IncidentResourceID { get; set; }
public int IncidentID { get; set; }
public int ResourceID { get; set; }
public virtual <Resource> Resource { get; set; }
}
In my Controllers, I have the following code:
[HttpPost]
public ActionResult Create(Incident incident)
{
//incident.Resources is returned as a valid object...
if (ModelState.IsValid)
{
db.Incidents.Add(incident);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(incident);
}
The above works perfectly! As I mentioned, the new Incident is inserted into the proper table, and all Resources assigned to the incident are added to the IncidentResources table.
However, the following code DOES NOT work this way for the edit...
[HttpPost]
public ActionResult Edit(Incident incident)
{
if (ModelState.IsValid)
{
//THE USER CAN ADD ADDITIONAL RESOURCES
foreach (IncidentResource r in incident.Resources)
{
r.IncidentID = incident.IncidentID;
}
db.Entry(incident).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(incident);
}
Again, the above seemingly does nothing to the IncidentResources table. Records are not added, removed, or updated. I don't receive an error either. It just doesn't do anything.
Please note that I DO NOT want to just trash the bridge table data and reinsert. I will have 1-to-many relationships to that data that I do not want to orphan.
What am I not understanding about how this works?