public async Task <Employee> CreateEmployeeAsync(Employee e) { // enforce the new immutable ID here, so if we expand to other consumers later the rule is still enforced if (string.IsNullOrEmpty(e.ImmutableId)) { e.ImmutableId = Guid.NewGuid().ToString(); } // since cosmos' auto-generated IDs are all guids, need to come up with a shorthand here that's easy for humans to use // todo: figure out something better than Random - sticking to 4 digits here for readability but obviously this would need to change // todo: at this point, it might be cheaper to just ping the DB with the ID to check for a result rather than wait for and catch an exception, although not found throws an exception too var r = new Random(); var empId = r.Next(0, 9999).ToString("D4"); e.CompanyId = empId; try { var employeeRecord = await _repo.CreateDocumentAsync(e); if (!employeeRecord.Success && employeeRecord.ErrorCode == "Conflict") { // retry, basically get a new ID because ours conflicted e = await CreateEmployeeAsync(e); } //todo : handle other error cases better than rethrowing else if (!employeeRecord.Success && employeeRecord.Exception != null) { throw employeeRecord.Exception; } else if (!employeeRecord.Success) { throw new Exception(employeeRecord.Message); } // todo: reconsider this, perhaps totally OOB photo uploading (for supporting multiple) //e = await SaveEmployeePhoto(e); return(e); } catch (Exception ex) { // todo: needs exception handling and retry for all these network calls Console.WriteLine(ex); } // todo: hate to return null return(null); }