I have two tables that are linked with a many to many relationship. MVC entity framework hides the linking table and ignores it when I try to insert a new linked object.
Tables are linked on personID and interventionID with a combined PK of those two.
I’m adding a new intervention that has an interventioID created as a new key. I have passed the personID to the controller and the debugger shows it with the correct value.
However, when I call:
db.tInterventions.Add(tintervention);
db.SaveChanges();
return RedirectToAction("Index");
…the link table doesn’t get filled.
The create method is as follows:
[HttpPost]
public ActionResult Create([Bind(Exclude = "interventionID")]tIntervention tintervention,
tPerson tperson,
int id,
int? personID)
How can I force the insert on the linking table?
The problem was down to the fact that PersonID is in optional parameter. Because the parameter isn’t required, the ModelState.IsValid would return True when the PersonID was populated but the value wasn’t being passed into the model.
I added a condition to check the personID and then did a Find/Bind of the person to the intervention as follows:
This might not be the best way to accomplish this but it works. Any further comments welcome.