I have a simple table setup
User
- Id
- Name
Role
- Id
- Name
UserRole
- UserId
- RoleId
Using Fluent I have the following relationship declared
this.HasMany(t => t.Roles)
.WithMany(s => s.Users)
.Map(m =>
{
m.ToTable("UserRole");
m.MapLeftKey("UserId");
m.MapRightKey("RoleId");
});
When I create a new User with multiple Role it adds them correctly in the Database. When I Update a User with Role's that don't already exist yet then it is OK.
I am having problems adding the following:
Existing Roles
Role A
Role B
Role C
I want to remove Role B thus leaving
Role A
Role C
I have tried a couple of things but I always end up with the "Additional information: Saving or accepting changes failed because more than one entity of type '...Role' have the same primary key value." or no deletion occurs at all.
Method 1
I have tried things like creating a method to delete all the Roles first then just adding the incoming Roles but for some reason it's maintaining the tracked changes and still sees the Roles that are deleted.
public ActionResult Edit(int userId, User user)
{
// clear roles
_userService.ClearRoles(userId);
_unitOfWork.Save();
// if I put a break here, I can see the roles being removed from the database
// update user with new roles
_userService.Update(id, user)
_unitOfWork.Save();
}
// _userService.Update
public void Update(int userId, User user)
{
User existingUser = Find(userId);
if (existingUser != null)
{
existingUser.Roles = user.Roles;
_userRepository.Update(existingUser);
}
}
public void ClearRoles(int userId)
{
User existingUser = GetUser(userId);
if(existingUser != null)
{
existingUser.Roles.ToList().ForEach(f => existingUser.Roles.Remove(f));
}
}
Method 2
I tried to remove the Role objects but no Roles get deleted, nothing happens
public ActionResult Edit(int userId, User user)
{
_userService.Update(id, user)
_unitOfWork.Save();
}
// _userService.Update
public void Update(int userId, User user)
{
User existingUser = Find(userId);
if (existingUser != null)
{
existingUser.Roles.ToList().ForEach(f => existingUser.Roles.Remove(f));
existingUser.Roles = user.Roles;
_userRepository.Update(existingUser);
}
}
Any further ideas on how to resolve this?