public async Task <IActionResult> AddAsync([FromBody] UserGroupAddModel mUserGroup) { if (!ModelState.IsValid) { return(HttpBadRequest(ModelStateError())); } var userGroupId = await _userGroupRepository.AddAsync(mUserGroup); return(CreatedAtRoute("GetByUserGroupIdAsync", new { controller = "UserGroups", userGroupId = userGroupId }, mUserGroup)); }
public async Task <int> AddAsync(UserGroupAddModel mUserGroup) { var group = _context.Groups.FirstOrDefault(c => c.GroupId == mUserGroup.GroupId); if (group == null) { throw new ExpectException("Could not find Group data which GroupId equal to " + mUserGroup.GroupId); } var user = _context.Users.FirstOrDefault(c => c.Id == mUserGroup.UserId); if (user == null) { throw new ExpectException("Could not find User data which UserId equal to '" + mUserGroup.UserId + "'"); } //GroupId and UserId must be unique var checkData = await _context.UserGroups .Where(c => c.GroupId == mUserGroup.GroupId && c.UserId == mUserGroup.UserId).ToListAsync(); if (checkData.Count > 0) { throw new ExpectException("There is already exist data which GroupId equal to " + mUserGroup.GroupId + " and UserId equal to '" + mUserGroup.UserId + "'"); } var model = new UserGroup { GroupId = mUserGroup.GroupId, UserId = mUserGroup.UserId }; _context.UserGroups.Add(model); await _context.SaveChangesAsync(); return(model.UserGroupId); }