public bool CreateJob(JobCreate model) { var service = _context.Services.Find(model.ServiceId); TimeSpan span; if (service.DurationUnit == DurationUnit.Minutes) { span = new TimeSpan(0, service.Duration, 0); } else { span = new TimeSpan(service.Duration, 0, 0); } var jobEntity = new Job { ClientId = model.ClientId, ServiceId = model.ServiceId, StartDate = model.StartDate, StartTime = model.StartTime, End = model.StartTime + span, Note = model.Note }; _context.Jobs.Add(jobEntity); int savedChangeToJobs = _context.SaveChanges(); var petIds = model.PetIds; int savedChangesToPetAssignments = 0; // Creating PetToJob assigments - need this becuase one job could have multiple pets and there could be multiple jobs for the same pet foreach (var petId in petIds) { var assignmentEntity = new PetToJob { PetId = petId, JobId = jobEntity.JobId }; _context.PetsToJobs.Add(assignmentEntity); savedChangesToPetAssignments += _context.SaveChanges(); } // CreateJob is succesful if one (from job save) plus the amount of pets on the job is equal the amount of saved changes return(savedChangeToJobs + savedChangesToPetAssignments == 1 + model.PetIds.Count()); }
public bool UpdateJob(JobEdit model) { var jobEntity = _context.Jobs.Find(model.JobId); jobEntity.ClientId = model.ClientId; jobEntity.ServiceId = model.ServiceId; jobEntity.StartDate = model.StartDate; jobEntity.StartTime = model.StartTime; jobEntity.Note = model.Note; int savedChangeToJobs = _context.SaveChanges(); var petAssignments = _context.PetsToJobs.Where(e => e.JobId == model.JobId); // Pets on job - Is model equal to persistence? List <int> petIds = petAssignments.Select(e => e.PetId).ToList(); bool areEqual = Enumerable.SequenceEqual(petIds.OrderBy(e => e), model.PetIds.OrderBy(e => e)); // If not, delete all and reassign if (!areEqual) { foreach (var petAssignment in petAssignments) { _context.PetsToJobs.Remove(petAssignment); } int savedChangesToPetAssignments = 0; foreach (var petId in model.PetIds) { var assignmentEntity = new PetToJob { PetId = petId, JobId = jobEntity.JobId }; _context.PetsToJobs.Add(assignmentEntity); savedChangesToPetAssignments += _context.SaveChanges(); } return(savedChangeToJobs + savedChangesToPetAssignments == 1 + model.PetIds.Count()); } return(savedChangeToJobs == 1); }