将用户添加到角色会将重复的用户插入用户表中
我首先使用实体框架代码来为我的用户管理数据库后台存储。我有一个“将角色添加到用户”操作,该操作从数据库中提取用户,将该用户添加到角色,然后保存更改。但是,当我执行此操作时,用户的新副本将使用新的/不同的 ID(唯一键)插入到数据库中,而不是我从数据库中提取的用户,我不确定为什么。对于为什么会发生这种情况有什么想法吗?
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只是猜测:您似乎对
_userRepository
和_roleRepository
有单独的 ObjectContext。通过从附加到此上下文的_userRepository
加载usersToGiveRole
。selectedRole
似乎附加到_roleRepository
的其他上下文。当您将user
添加到selectedRole.UsersWithRole
时,您将其添加到第二个上下文中(user
现在位于added
中) _roleRepository 上下文中的状态)。当您调用此上下文的SaveChanges
时,现在会在数据库中创建一个新的 User 对象。解决方案:确保在两个存储库中仅使用一个上下文。
编辑
简而言之,我的意思是:
不要这样做:
而是这样做:
上下文(或工作单元)始终是一个级别在存储库之上,应该在外部创建并注入到存储库中。
Just a guess: You seem to have separate ObjectContexts for
_userRepository
and for_roleRepository
. By loadingusersToGiveRole
from the_userRepository
you attach to this context.selectedRole
seems to be attached to the other context of_roleRepository
. When you add theuser
toselectedRole.UsersWithRole
you add it to this second context (user
is now inadded
state in the context of_roleRepository
). When you callSaveChanges
of 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.