There is a many to many relationship between User and Roles. I can easily add the Role to the many to many table, but I cannot remove it, it does not give me any error but don't remove the roles to remove. I try everything I found. Here is my code.
public User Update(User entity)
{
using (var context = new EnerSysEntities())
{
var user = context.Users.Single(u => u.USER_ID == entity.USER_ID);
//All roles in the data base
List<Role> roleAlreadyAssigned = GetById(entity.USER_ID).Roles.ToList();
//Roles to remove
List<Role> rolesToRemove =
roleAlreadyAssigned.Where(x => entity.Roles.All(y => y.ROLE_ID != x.ROLE_ID)).ToList();
//Roles to add
List<Role> rolesToAdd =
entity.Roles.Where(x => roleAlreadyAssigned.All(y => y.ROLE_ID != x.ROLE_ID)).ToList();
foreach (Role roleToDelete in rolesToRemove.ToList())
{
// Remove the roles from rolesToRemove
user.Roles.Remove(roleToDelete);
}
//Add the roles which are not in the list of rolesToAdd
foreach (Role rol in rolesToAdd)
{
var newRole = new Role { ROLE_ID = rol.ROLE_ID };
context.Roles.Attach(newRole);
user.Roles.Add(newRole);
}
context.SaveChanges();
return entity;
}
}
What I'm missing?
To remove entities from Entity it's necessary that this entities were loaded before in your Entity.
Try with