public Case createAndPersistAsync(CreateCaseDTO dto) { Case result = new Case(); List <string> specimenIds = new List <string>(); foreach (CreateSpecimenDTO spDTO in dto.Specimens) { List <CreateSlideDTO> slideDTOs = spDTO.Slides; spDTO.Slides = null; List <string> slideIDs = new List <string>(); Specimen sp = specimenFactory.create(spDTO); if (slideDTOs != null) { foreach (CreateSlideDTO createSlideDTO in slideDTOs) { Slide slide = slideFactory.create(createSlideDTO); slide.CreatedOn = DateTime.Now; Document slideDoc = slideRepository.Save(slide); slideIDs.Add(slideDoc.GetPropertyValue <string>("id")); } } sp.CreatedOn = DateTime.Now; sp.Slides = slideIDs; Console.WriteLine("Spec: " + JsonConvert.SerializeObject(sp)); Document doc = specimenRepository.Save(sp); Console.WriteLine("DOC: " + JsonConvert.SerializeObject(doc)); specimenIds.Add(specimenFactory.create(doc).Id); } Requestor r = requestorFactory.create(dto.Requestor); r.CreatedOn = DateTime.Now; Document reqDoc = requestorRepository.Save(r); Requestor requestor = requestorFactory.create(reqDoc); Patient p = patientFactory.create(dto.Patient); p.CreatedOn = DateTime.Now; p.PatientId = patientRepository.GetCountAsync() + 1; Patient patient = patientFactory.create(patientRepository.Save(p)); result.Specimens = specimenIds; result.RequestorId = requestor.Id; result.PatientId = patient.Id; result.Type = dto.Type; result.CaseId = CaseType.GetCode(result.Type) + caseRepository.GetCountByTypeAsync(result.Type).ToString().PadLeft(5, '0'); result.SetPropertyValue("CreatedOn", DateTime.Now); result.Status = CaseStatus.Open; caseRepository.Save(result); List <Specimen> specimens = specimenRepository.ListAsync(specimenIds).Result; int specimenCount = 1; foreach (Specimen sp in specimens) { sp.SetPropertyValue("SpecimenId", result.CaseId + "-" + specimenCount.ToString()); List <Slide> slds = slideRepository.ListAsync(sp.Slides).Result; int slidesCount = 1; foreach (Slide s in slds) { s.SetPropertyValue("SlideId", result.CaseId + "-" + specimenCount.ToString() + "-" + sp.BlockId + "-" + slidesCount); slideRepository.FullUpdate(s); } specimenRepository.FullUpdate(sp); specimenCount++; } return(result); }