I am trying to create a program where that only one user can be in only one role at a time. I have developed a clunky means of removing the previously held role and then inserting the new role, but I do not like t开发者_如何转开发his.
I attempted to do this at the database level, one-to-many instead of many-to-many in the UsersInRoles table but I only seem to only have success in breaking the 'built-in' role management system. Using System.Web.Security.SqlRoleProvider
Just feel there is a more elegant solution as I am new to MVC but I cannot think of it.
Anyone have a suggestion?
Why not do something like this. i.e. make it so adding a user to a role removes them from all others.
public class SingleRoleProvider : SqlRoleProvider
{
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
// remove any existing roles users belong to
RemoveUsersFromRoles(usernames, GetAllRoles());
//only accept first role, your app should only be adding one at a time
base.AddUsersToRoles(usernames, roleNames.Take(1));
}
}
You obviously can't change the database schema and expect the default role provider to work. You will probably have to create a new one (you can use the source code available from MS to base your changes if you like).
精彩评论