Lets say i have a Person
table, a Role
table with a trel table PersonRoles
linking them as many to many.
I create a new person and assign them to 2 roles (role 1, role 3).
I then want to edit this person; so i retrieve their data and bind their roles to a checkboxes. I change the values (Deselect role 1 and select role 2 instead) I then post this data back through a viewmodel.
Can i then get Entity Framework to update these roles for me, as in delete the entry in PersonRoles
to role 1 and then add a new entry as role 2? Or do i have to do the logic for this myself?
Something like ** this ** i was hopeing but doesn't work obviously.
[HttpPost]
public ActionResult Edit(int id, PersonViewModel model)
{
if (ModelState.IsValid)
{
var person= GetPerson(id);
person.Name= model.Name;
person.Age = model.Age;
ICollection<Roles> personroles = new Collection<Roles>();
foreach (string rId in model.Roles)
{
personroles.Add(this.RoleRepository.Single(r => r.Id.ToString() == rId));
}
**person.Roles = personroles;**
this.PersonRepository.SaveChanges();
return RedirectToIndex(personId);
}
return View();
}
Cheers, Kohan