Example #1
0
        public bool EditContactById(int contactId, ContactDto contact)
        {
            try
            {
                this.addressRepository = new AddressRepository(_dbContext);
                var contactTmp = _dbContext.Contact.FirstOrDefault(x => x.Contact1 == contactId);
                if (contactTmp != null)
                {
                    if (contact.Address != null)
                    {
                        DC.AddressRepository.AddressDto addresss = null;
                        addresss          = addressRepository.CreateAddress(contact.Address);
                        contact.AddressId = addresss.AddressId;
                    }

                    contactTmp.FirsttName   = contact.FirsttName;
                    contactTmp.LastName     = contact.LastName;
                    contactTmp.ModifiedDate = DateTime.Now;
                    contactTmp.AddressId    = contact.AddressId;
                    //delete all phones and emails
                    _dbContext.RemoveRange(_dbContext.Phone.Where(x => x.ContactId == contactTmp.Contact1));
                    _dbContext.RemoveRange(_dbContext.Email.Where(x => x.ContactId == contactTmp.Contact1));
                    //create new phones and emails
                    foreach (var emailDto in contact.Emails)
                    {
                        _dbContext.Add(new Email()
                        {
                            ContactId = contactTmp.Contact1, EmailAddress = emailDto.EmailAddress
                        });
                    }
                    foreach (var phoneDto in contact.Phones)
                    {
                        _dbContext.Add(new Phone()
                        {
                            ContactId = contactTmp.Contact1, PhoneNumber = phoneDto.PhoneNumber
                        });
                    }
                    _dbContext.SaveChanges();
                    return(true);
                }
                return(false);
            }
            catch (Exception ex)
            {
                //log ex
                throw new Exception(ex.Message);
            }
        }