public async Task <IActionResult> AddTrainer(TrainerInputModel input) { try { await this.administrationService.AddTrainer(input); } catch (Exception e) { this.ModelState.AddModelError("admin", e.Message); } if (!this.ModelState.IsValid) { return(this.View()); } return(this.Redirect("/")); }
public async Task AddTrainer(TrainerInputModel input) { var user = await this.db.Users.FirstOrDefaultAsync(c => c.Email == input.Email); if (user == null) { throw new ArgumentException("Няма регистриран човек с този е-мейл."); } var asTrainer = user as Trainer; if (asTrainer != null) { throw new ArgumentException("Този човек вече е треньор."); } var newRoles = new List <IdentityUserRole <string> >(); var userRoles = await this.db.UserRoles.Where(ur => ur.UserId == user.Id).ToListAsync(); newRoles.AddRange(userRoles); this.db.UserRoles.RemoveRange(userRoles); await this.db.SaveChangesAsync(); this.db.Users.Remove(user); string fileName = this.UploadImage(input.ProfileImage, "trainerImages"); var trainer = new Trainer() { UserName = user.UserName, Roles = user.Roles, Claims = user.Claims, TwoFactorEnabled = user.TwoFactorEnabled, PhoneNumber = user.PhoneNumber, ConcurrencyStamp = user.ConcurrencyStamp, NormalizedEmail = user.NormalizedEmail, Email = user.Email, NormalizedUserName = user.NormalizedUserName, EmailConfirmed = user.EmailConfirmed, SecurityStamp = user.SecurityStamp, PasswordHash = user.PasswordHash, PhoneNumberConfirmed = user.PhoneNumberConfirmed, Logins = user.Logins, FirstName = input.FirstName, LastName = input.LastName, ProfilePictureUrl = fileName, }; var trainerRoleId = (await this.db.Roles.FirstOrDefaultAsync(r => r.Name == GlobalConstants.TrainerRoleName)).Id; await this.db.Trainers.AddAsync(trainer); await this.db.SaveChangesAsync(); newRoles.ForEach(r => r.UserId = trainer.Id); newRoles.Add(new IdentityUserRole <string>() { UserId = trainer.Id, RoleId = trainerRoleId, }); await this.db.UserRoles.AddRangeAsync(newRoles); await this.db.SaveChangesAsync(); }