public async Task <IActionResult> UpdateUser([FromBody] ApplicationUserIn EntityIn) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var MyEntity = _context.ApplicationUser .Include(x => x.ApplicationUserRoles) .ThenInclude(x => x.ApplicationRole) .FirstOrDefault(x => x.Id == EntityIn.Id) ; if (MyEntity == null) { return(BadRequest()); } try { //Process Roles - Delete all current roles and only add the ones they selected if (EntityIn.ApplicationUserRoles != null && EntityIn.ApplicationUserRoles.Count() > 0) { _context.ApplicationUserRole.RemoveRange(MyEntity.ApplicationUserRoles); //_context.SaveChanges(); } _mapper.Map(EntityIn, MyEntity); //Null Roles so only the ApplicationUser is updated below MyEntity.ApplicationUserRoles = new List <ApplicationUserRole>(); //Add in Roles chosen in the UI foreach (var role in EntityIn.ApplicationUserRoles) { MyEntity.ApplicationUserRoles.Add(new ApplicationUserRole() { UserId = EntityIn.Id, RoleId = role.ApplicationRole.Id }); } _context.Update(MyEntity); await _context.SaveChangesAsync(); } catch (Exception ex) { throw ex; } return(Ok()); }
public async Task <IActionResult> Create([FromBody] ApplicationUserIn EntityIn) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } try { var MyNewEntity = new ApplicationUser(); _mapper.Map(EntityIn, MyNewEntity); MyNewEntity.ApplicationUserRoles = null; //Set email the same as username MyNewEntity.Email = MyNewEntity.UserName; MyNewEntity.DateCreated = DateTime.Now; MyNewEntity.DateLastModified = DateTime.Now; var myResult = await _userManager.CreateAsync(MyNewEntity); if (!myResult.Succeeded) { string myErrors = ""; foreach (var error in myResult.Errors) { myErrors = myErrors + error.Description; } return(BadRequest(myErrors)); } //_context.ApplicationUser.Add(MyNewEntity); //await _context.SaveChangesAsync(); //Add in Roles chosen in the UI foreach (var role in EntityIn.ApplicationUserRoles) { _context.ApplicationUserRole.Add(new ApplicationUserRole() { UserId = MyNewEntity.Id, RoleId = role.ApplicationRole.Id }); } await _context.SaveChangesAsync(); //Get User and Roles to send back for the list var myNewUser = _context.ApplicationUser .Include(x => x.ApplicationUserRoles) .ThenInclude(x => x.ApplicationRole) .FirstOrDefault(x => x.Id == MyNewEntity.Id); var myApplicationUserOut = new ApplicationUserOut(); myApplicationUserOut = _mapper.Map <ApplicationUserOut>(myNewUser); return(Ok(myApplicationUserOut)); } catch (Exception ex) { throw ex; } }