public async Task <IActionResult> Create(HotelRegisterViewModel model) { model.Image = this.Request.Form.Files["image"]; await this.hotelService.CreateAsync(model); return(this.Redirect("/Home/Index")); }
public async Task CreateAsync(HotelRegisterViewModel model) { var imageUrl = string.Empty; if (model.Image != null && model.Image.Length > 0) { var fileName = Path.GetFileName(model.Image.FileName); var filePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", fileName); using var fileStream = new FileStream(filePath, FileMode.Create); await model.Image.CopyToAsync(fileStream); var account = new Account { ApiKey = "597981955165718", ApiSecret = "YrIRgn7E7ffUnN1kXSJhyGQJS54", Cloud = "hotelcollab" }; fileStream.Close(); var cloudinary = new Cloudinary(account); var uploadParams = new ImageUploadParams() { File = new FileDescription(filePath), }; var result = cloudinary.Upload(uploadParams); File.Delete(filePath); imageUrl = result.Url.ToString(); } var towns = await this.townRepo.GetAllAsync(); towns = towns .Where(town => town.Name == model.TownName).ToList(); Town town; if (!towns.Any()) { town = new Town { Name = model.TownName, }; await this.townRepo.AddAsync(town); } else { town = towns.FirstOrDefault(); } var hotel = new Hotel(imageUrl) { Name = model.Name, PhoneNumber = model.PhoneNumber, Address = model.Address, CleaningPeriod = model.CleaningPeriod, TownId = town.Id, }; town.Hotels.Add(hotel); foreach (var role in await this.roleRepo.GetAllAsync()) { hotel.HotelRoles.Add(new HotelRole { HotelId = hotel.Id, RoleId = (await this.roleRepo.GetAllAsync()).FirstOrDefault(r => r.Name == role.Name)?.Id, }); } await this.townRepo.SaveChangesAsync(); await this.hotelRepo.SaveChangesAsync(); await this.userHotelRoleRepo.AddAsync(new UserHotelRole { UserId = this.httpContextAccessor.HttpContext.User.FindFirst("Id").Value, HotelRoleId = hotel.HotelRoles.FirstOrDefault(hr => hr.Role.Name == "Manager").Id, }); await this.userHotelRoleRepo.SaveChangesAsync(); }