public async Task <ActionResult <User> > PostUser(User user) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } try { var userGroup = _context.UserGroups.Single(x => x.Group.Equals("User")); _context.Users.Add(user); await _context.SaveChangesAsync(); var userHasUserGroup = new UserHasUserGroup { UserId = user.Id, UserGroupId = userGroup.Id }; _context.UserHasUserGroups.Add(userHasUserGroup); await _context.SaveChangesAsync(); return(CreatedAtAction("GetUser", new { id = user.Id }, user)); } catch (InvalidOperationException) { Debug.WriteLine( "ERROR: Duplicate user groups. Delete all values in user groups table and try again"); return(NoContent()); } } catch (SqlException) { return(StatusCode(503, null)); } }
public async Task <IActionResult> AddUserGroupToUser([FromRoute] int userId, [FromRoute] int userGroupId) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (!UserExists(userId)) { return(NoContent()); } if (UserHasUserGroupExists(userId, userGroupId)) { return(NoContent()); } var userHasUserGroup = new UserHasUserGroup { UserId = userId, UserGroupId = userGroupId }; _context.UserHasUserGroups.Add(userHasUserGroup); await _context.SaveChangesAsync(); return(CreatedAtAction("GetUserHasUserGroup", new { userId, userGroupId }, userHasUserGroup)); } catch (SqlException) { return(StatusCode(503, null)); } }