public PitchCreateViewModel GetPitchWithId(Guid id) { Pitch pitch = _context.Pitch.Where(x => x.Id == id).Include(x => x.PitchOpenHours).FirstOrDefault(); if (pitch == null) { return(null); } PitchCreateViewModel result = new PitchCreateViewModel() { Id = pitch.Id, LocalisationX = pitch.LocalisationX, LocalisationY = pitch.LocalisationY, Name = pitch.Name, SpotNumber = (int)pitch.SpotNumber, EndHours = "", StartHours = "", WeekDays = "" }; var openHours = pitch.PitchOpenHours.OrderBy(x => ((int)x.WeekDay)).ThenBy(x => x.StartHour).Where(x => !x.IsArchived); foreach (var openHour in openHours) { result.EndHours += openHour.EndHour + ";"; result.StartHours += openHour.StartHour + ";"; result.WeekDays += ((int)openHour.WeekDay).ToString() + ";"; } return(result); }
public async Task UpdatePitch(PitchCreateViewModel pitch) { using (var transaction = await _context.Database.BeginTransactionAsync()) { try { Pitch updatedPitch = _context.Pitch.Where(x => x.Id == pitch.Id).First(); updatedPitch.LocalisationX = pitch.LocalisationX; updatedPitch.LocalisationY = pitch.LocalisationY; updatedPitch.Name = pitch.Name; updatedPitch.SpotNumber = pitch.SpotNumber; _context.Pitch.Update(updatedPitch); string[] weekDays = pitch.WeekDays.Split(";"); string[] startHours = pitch.StartHours.Split(";"); string[] endHours = pitch.EndHours.Split(";"); var allOpenHours = _context.PitchOpenHours; var oldRecords = _context.PitchOpenHours.Where(x => x.PitchId == pitch.Id); foreach (var record in oldRecords) { record.IsArchived = true; } for (int i = 0; i < weekDays.Length - 1; i++) { var record = allOpenHours.Where(x => x.PitchId == updatedPitch.Id && x.WeekDay == int.Parse(weekDays[i]) && x.EndHour == endHours[i] && x.StartHour == startHours[i]).FirstOrDefault(); if (record == null) { PitchOpenHours openHours = new PitchOpenHours() { Id = Guid.NewGuid(), PitchId = pitch.Id, WeekDay = int.Parse(weekDays[i]), EndHour = endHours[i], StartHour = startHours[i] }; _context.PitchOpenHours.Add(openHours); } else { record.IsArchived = false; } } _context.SaveChanges(); transaction.Commit(); } catch (Exception e) { throw e; } } }
public async Task <IActionResult> Edit(PitchCreateViewModel pitch) { if (!ModelState.IsValid) { return(View(pitch)); } await _pitchService.UpdatePitch(pitch); return(RedirectToAction("Index", "Pitch")); }