Reputation: 41
I am working on an ASP MVC application with EF5. We are trying to update a User object, which contains a list of permissions, groups and a foreign key for the Role object. The problem we're facing is that while the permissions, groups, user password etc. all get updated, the role does not. We have searched on SO for several hours now but can't seem to implement a working solution. When trying to update our user, the Role gets passed along properly but does not get updated in the database.
Below, you can find the Post for our Edit page. We have already tried attaching it to our db (which is the database context), creating a new context to attach it to and several other answers to no avail. Simply put, we're stumped and have no idea how to pass along the updated role to our database. Many thanks in advance for reading and hopefully replying.
// POST: /User/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(User user, string[] selectedPermissions, string[] selectedGroups)
{
var userInDb = db.Users.Find(user.Id);
if (selectedPermissions != null || selectedGroups != null)
{
user.Permissions = userInDb.Permissions;
user.Groups = userInDb.Groups;
}
if (user.Username != null && user.Password != null && user.Role != null && user.Person != null)
{
user.Person = db.People.Find(user.Person.IdCardNumber);
user.Person = db.People.Find(user.Person.IdCardNumber);
user.Role = db.Roles.Find(user.Role.Id);
SavePerms(selectedPermissions, user);
SaveGroups(selectedGroups, user);
db.Entry(userInDb).CurrentValues.SetValues(user);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
Upvotes: 1
Views: 248
Reputation: 177163
userInDb
is the tracked entity, not user
. Therefore you should set the new role to userInDb
so that EF can track the change of the Role
property:
userInDb.Role = db.Roles.Find(user.Role.Id);
Upvotes: 1