I’m using Entity Framework code first to manage a database backstore for my users. I have an “add role to user” operation that pulls a user from the db, adds that user to the role, and then saves changes. However, when I do this a new copy of the user is inserted into the database with a new/different ID (unique key) than the user I pulled from the db and I’m not sure why. Any thoughts on why this is happening?
IEnumerable<long> usersIdsToGiveRole = from u in vm.UsersNotInSelectedRole where u.IsSelected select u.Id; // say, yields "5"
IEnumerable<User> usersToGiveRole = _userRepository.InternalUsers.Where(u => usersIdsToGiveRole.Contains(u.ID)); // gets user with ID 5
foreach (var user in usersToGiveRole)
{
selectedRole.UsersWithRole.Add(user);
}
_roleRepository.SaveChanges(); // creates new user with ID 6 cloning all other fields of user 5
Just a guess: You seem to have separate ObjectContexts for
_userRepositoryand for_roleRepository. By loadingusersToGiveRolefrom the_userRepositoryyou attach to this context.selectedRoleseems to be attached to the other context of_roleRepository. When you add theusertoselectedRole.UsersWithRoleyou add it to this second context (useris now inaddedstate in the context of_roleRepository). When you callSaveChangesof this context now a new User object is created in the database.Solution: Make sure that you only use one single context in both repositories.
Edit
In short what I mean:
Don’t do this:
Instead do this:
The context (or Unit of Work) is always a level above the repositories, should be created outside and injected into the repos.