[英]Entity Framework Code First: Many-to-Many relationship; Remove some Roles from the User
I have a Many-to-Many User/Role relationship. 我有一个多对多用户/角色关系。
It's OK, when I insert a new user into the database and add it in some roles. 可以,当我在数据库中插入新用户并将其添加为某些角色时。
But, how to remove some roles from the user? 但是,如何从用户中删除某些角色? I don't want to completely remove user or role, I only want to: 1. Remove some Roles from the User;
我不想完全删除用户或角色,我只想:1.从用户中删除一些角色; 2. Assign new Roles to the User.
2.为用户分配新角色。
My Classes: 我的课程:
public class User
{
public int Id { get; set; }
public virtual string UserName { get; set; }
public virtual string Password { get; set; }
public List<Role> Roles { get; set; }
}
public class Role
{
public int Id { get; set; }
public virtual string Name { get; set; }
public List<User> Users { get; set; }
}
I'm not entirely clear on what you are asking for, but I think it is that you want to be able to remove a role from a user, and that user from the appropriate role? 我对您的要求尚不完全清楚,但我认为这是您希望能够从用户中删除角色,以及将该用户从相应角色中删除?
If so, you will know the user and role, and for this simple case want to make use of the List.Remove function. 如果是这样,您将知道用户和角色,并且在这种简单情况下,您想使用List.Remove函数。
void RemUserRole(User u, Role r)
{
u.Roles.Remove(r);
r.Users.Remove(u);
}
This will remove the items from the relevant list of each Role and User. 这将从每个角色和用户的相关列表中删除项目。
Edit: 编辑:
To add new roles to users, you use the List.Add method. 要向用户添加新角色,请使用List.Add方法。
void AddUserRole(User u, Role r)
{
u.Roles.Add(r);
r.Users.Add(u);
}
This simply adds each item to the other's list of roles/users. 这只是将每个项目添加到对方的角色/用户列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.