public override void AddUsersToRoles(string[] usernames, string[] roleNames) { using (UsersContext db = new UsersContext()) { foreach (string username in usernames) { foreach (string rolename in roleNames) { UserInRole userInRole = new UserInRole(); userInRole.UserName = (string)Membership.GetUser(username).ProviderUserKey; userInRole.RoleId = db.Roles.FirstOrDefault(x => x.Name == rolename).Id; db.UsersInRoles.Add(userInRole); db.SaveChanges(); } } } }
public override void AddUsersToRoles(string[] usernames, string[] roleNames) { using (UsersContext db = new UsersContext()) { foreach (string username in usernames) { foreach (string rolename in roleNames) { UserInRole userInRole = new UserInRole(); userInRole.UserName = (string) Membership.GetUser(username).ProviderUserKey; userInRole.RoleId = db.Roles.FirstOrDefault(x => x.Name == rolename).Id; db.UsersInRoles.Add(userInRole); db.SaveChanges(); } } } }
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { using (UsersContext db = new UsersContext()) { List <UserInRole> usersInRoles = new List <UserInRole>(); for (int i = 0; i < usernames.Count(); i++) { string userName = usernames[i]; for (int j = 0; j < roleNames.Count(); j++) { string roleName = roleNames[j]; int roleId = (int)db.Roles.FirstOrDefault(x => x.Name == roleName).Id; UserInRole userInRole = db.UsersInRoles.FirstOrDefault(x => x.UserName == userName && x.RoleId == roleId); usersInRoles.Add(userInRole); } } db.UsersInRoles.RemoveRange(usersInRoles); db.SaveChanges(); } }