// ************************************** // UpdateUserCatalogRole // ************************************** public static void UpdateUserCatalogRole(int userId, int catalogId, int roleId) { using (var ctx = new SongSearchContext()) { var user = ctx.GetUserDetail(userId); if (user != null && catalogId > 0) { var usrCatalogRole = user.UserCatalogRoles.Where(c => c.CatalogId == catalogId).SingleOrDefault(); if (usrCatalogRole == null) { if (roleId > 0) { // new catalog role // check role against enum roleId = ModelEnums.GetRoles().GetBestMatchForRole(roleId); usrCatalogRole = new UserCatalogRole { UserId = userId, CatalogId = catalogId, RoleId = roleId }; ctx.UserCatalogRoles.AddObject(usrCatalogRole); } } else { if (roleId > 0) { // update role usrCatalogRole.RoleId = roleId; } else { //also remove these catalogs from any child users, really? var childUsers = user.MyUserHierarchy(withCatalogRoles: true); foreach (var child in childUsers) { var cat = ctx.UserCatalogRoles.SingleOrDefault(x => x.CatalogId == catalogId && x.UserId == child.UserId); if (cat != null) { ctx.UserCatalogRoles.DeleteObject(cat); } } // revoke parent access ctx.UserCatalogRoles.DeleteObject(usrCatalogRole); } } // check if it's an admin role; if so, elevate the system role to Admin if user is not already there if (roleId == (int)Roles.Admin && user.RoleId > roleId) { user.RoleId = roleId; ctx.AddToAdminBalance(user); } ctx.SaveChanges(); } } }