Using MVC3.0 with the razor view engine. I have an entity titled “Vendors” which contains a many to many reference to another entity called “Contacts”. All I want to do is remove all of the references from a vendor in a specific controller. Here is my code:
public ActionResult _Edit(Vendor vendor)
{
if (ModelState.IsValid)
{
//Clear contact list
vendor.Contacts.Clear();
db.Vendors.Attach(vendor);
db.ObjectStateManager.ChangeObjectState(vendor, EntityState.Modified);
db.SaveChanges();
}
}
For some reason this doesn’t work. and I am not sure why? Thanks
You should load vendor and its contacts from database, then update its properties and SaveChanges:
I know it is not as efficient as attaching entity and saving state, but no one said EF is perfect.
By the way, direct binding to Entity Framework object can be very dangerous. Malicious user can prepare POST with values, that are not present in form you provided for him and change values of field, that you didn’t want to be even modified in this action. You should create special view models.