public async Task <Response> CreateResponseAsync() { try { ContactDto resultContact = await contactsService.CreateOrEditContactAsync( ContactConverter.GetContactDto(request.Contact, clientConnection.UserId.GetValueOrDefault())).ConfigureAwait(false); return(new ContactsResponse(request.RequestId, ContactConverter.GetContactVm(resultContact))); } catch (ObjectDoesNotExistsException ex) { Logger.WriteLog(ex); return(new ResultResponse(request.RequestId, "User not found.", ObjectsLibrary.Enums.ErrorCode.ObjectDoesNotExists)); } }
public async Task <ContactDto> CreateOrEditContactAsync(ContactDto contactDto) { try { using (MessengerDbContext context = contextFactory.Create()) { Contact result; var contact = await context.Contacts .Include(opt => opt.ContactGroups) .FirstOrDefaultAsync(opt => opt.UserId == contactDto.UserId && opt.ContactUserId == contactDto.ContactUserId) .ConfigureAwait(false); if (contact == null) { Contact newContact = new Contact { Name = contactDto.Name, UserId = contactDto.UserId, ContactUserId = contactDto.ContactUserId, ContactId = contactDto.ContactId }; await context.Contacts.AddAsync(newContact).ConfigureAwait(false); result = newContact; } else { contact.Name = contactDto.Name; context.Update(contact); result = contact; } await context.SaveChangesAsync().ConfigureAwait(false); return(ContactConverter.GetContactDto(result)); } } catch (PostgresException ex) { if (ex.SqlState == "23503") { throw new ObjectDoesNotExistsException("User not found.", ex); } throw new InternalErrorException("Database error.", ex); } }