Ejemplo n.º 1
0
        public async Task <IActionResult> Edit(string id, [Bind("Id,UserId,RoleId")] UserRole userRole)
        {
            if (id != userRole.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    // 重复判断 是否存在UserId和RoleId的关系
                    if (await UserRoleManager.Exist(ur => ur.RoleId == userRole.RoleId && ur.UserId == userRole.UserId))
                    {
                        ModelState.AddModelError("All", "角色已经被绑定在该用户上");
                        ViewData["RoleId"] = new SelectList(RoleManager.Find(), nameof(Role.Id), nameof(Role.Name), userRole.RoleId);
                        ViewData["UserId"] = new SelectList(UserManager.Find(), nameof(Entitys.User.Id), nameof(Entitys.User.SignName), userRole.UserId);
                        return(View(userRole));
                    }
                    else
                    {
                        await UserRoleManager.Update(userRole);
                    }
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!await UserRoleManager.Exist(ur => ur.Id == userRole.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["RoleId"] = new SelectList(RoleManager.Find(), nameof(Role.Id), nameof(Role.Name), userRole.RoleId);
            ViewData["UserId"] = new SelectList(UserManager.Find(), nameof(Entitys.User.Id), nameof(Entitys.User.SignName), userRole.UserId);
            return(View(userRole));
        }