コード例 #1
0
        public async Task <IActionResult> DeleteConfirmed(int id)
        {
            var defaultId = _context.Perfil.SingleOrDefault(m => m.IsDefault == 1).IdPerfil;

            if (id == 1 || id == defaultId)
            {
                return(View("AccessDenied"));
            }
            var Perfil = await _context.Perfil.SingleOrDefaultAsync(m => m.IdPerfil == id);

            var users = await _context.ApplicationUsers.Where(u => u.IdPerfil == id).ToListAsync();

            List <ProfileRole> default_profileroles = await _context.ProfileRole
                                                      .Where(p => p.IdPerfil == defaultId)
                                                      .ToListAsync();

            foreach (ApplicationUsers user in users)
            {
                user.IdPerfil = defaultId;
                _context.ApplicationUsers.Attach(user);
                _context.Entry(user).Property(p => p.IdPerfil).IsModified = true;
                var roles = await _userManager.GetRolesAsync(user);

                await _userManager.RemoveFromRolesAsync(user, roles.ToArray());

                foreach (ProfileRole role in default_profileroles)
                {
                    string role_name = _roleManager.FindByIdAsync(role.RoleId).Result.Name;
                    if (await _roleManager.RoleExistsAsync(role_name))
                    {
                        await _userManager.AddToRoleAsync(user, role_name);
                    }
                }
            }
            var profileroles = await _context.ProfileRole.Where(p => p.IdPerfil == id).ToListAsync();

            _context.RemoveRange(profileroles);
            _context.Perfil.Remove(Perfil);
            await _context.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }