public async Task <ActionResult <EventViewModel> > Create([FromBody] CreateEventBody createEventBody) { try { Logger.LogInformation("{Id} is creating an event called {Name}", createEventBody.HostId, createEventBody.Name); var result = await EventService.Create(createEventBody); return(result); } catch (Exception e) { Logger.LogInformation(e.ToString()); return(BadRequest(e)); } }
/// <inheritdoc /> /// <exception cref="UserNotFoundException">Thrown when the user is not found</exception> public async Task <EventViewModel> Create(CreateEventBody createEventBody) { var host = await ApplicationContext.Users.AsSplitQuery().Include(x => x.HostedEvents) .FirstOrDefaultAsync(x => x.Id == createEventBody.HostId); if (host == null) { Logger.LogInformation("User not found"); throw new UserNotFoundException(); } // get coordinates of the address if (createEventBody.Address != null) { var cords = await GetAddressCords(createEventBody.Address); createEventBody.Address.Lat = cords.Lat; createEventBody.Address.Lon = cords.Lon; } var newEvent = new Event() { Name = createEventBody.Name, Description = createEventBody.Description, // Address = new Address(), isCanceled = false, Price = createEventBody.Price, IsOnline = createEventBody.IsOnline, EndLocal = createEventBody.EndLocal, EndUTC = createEventBody.EndLocal.ToUniversalTime(), StartLocal = createEventBody.StartLocal, StartUTC = createEventBody.StartLocal.ToUniversalTime(), Images = createEventBody.Images.Select(x => Mapper.Map <Image>(x)).ToList(), Thumbnail = createEventBody.Thumbnail != null ? Mapper.Map <Image>(createEventBody.Thumbnail) : new Image(), SocialLinks = createEventBody.SocialLinks != null ? createEventBody.SocialLinks.Select(x => Mapper.Map <SocialLink>(x)).ToList() : new List <SocialLink>(), TicketsLeft = createEventBody.NumberOfTickets, Created = new DateTime(), Finished = false }; // generate tickets for event List <Ticket> tickets = new List <Ticket>(); for (int i = 0; i < createEventBody.NumberOfTickets; i++) { tickets.Add(new Ticket() { Event = newEvent, Available = true, Uses = 0 }); } host.HostedEvents.Add(newEvent); try { // Saving user to Db. await ApplicationContext.Events.AddAsync(newEvent); await ApplicationContext.Tickets.AddRangeAsync(tickets); await ApplicationContext.SaveChangesAsync(); if (createEventBody.Categories != null) { List <EventCategory> eventCategories = createEventBody.Categories .Select(c => new EventCategory() { CategoryId = c.Id, EventId = newEvent.Id }).ToList(); await ApplicationContext.AddRangeAsync(eventCategories); await ApplicationContext.SaveChangesAsync(); } return(Mapper.Map <EventViewModel>(newEvent)); } catch { Logger.LogWarning("User failed to save"); throw; } }