public void Delete(Client entity)
 {
     _context.Entry(entity).State = EntityState.Deleted;
 }
        public Clients Update(int id, Clients client)
        {
            string photo = "";

            using (var fu = new ImageUploader(client.Image))
            {
                photo = fu.SaveFile(_env.ContentRootPath);
            }

            client.Photo = photo;


            var existingClient = _context.Clients.Where(p => p.ClientId == id).Include(p => p.PhoneNumbers).SingleOrDefault();

            _context.Entry(existingClient).CurrentValues.SetValues(client);

            // update phone numbers
            foreach (var item in existingClient.PhoneNumbers.ToList())
            {
                if (!client.PhoneNumbers.Any(c => c.PhoneNumberId == item.PhoneNumberId))
                {
                    _context.PhoneNumbers.Remove(item);
                }
            }

            foreach (var phoneNumber in client.PhoneNumbers)
            {
                var existingNumber = existingClient.PhoneNumbers
                                     .Where(c => c.PhoneNumberId == phoneNumber.PhoneNumberId)
                                     .SingleOrDefault();

                if (phoneNumber.PhoneNumberId == 0)
                {
                    existingNumber = null;
                }

                if (existingNumber != null)
                {
                    _context.Entry(existingNumber).CurrentValues.SetValues(phoneNumber);
                }
                else
                {
                    existingClient.PhoneNumbers.Add(phoneNumber);
                }
            }

            // update relations
            foreach (var item in existingClient.RelatedClientsClient.ToList())
            {
                if (!client.RelatedClientsClient.Any(c => c.RelatedClientsId == item.RelatedClientsId))
                {
                    _context.RelatedClients.Remove(item);
                }
            }

            foreach (var relatedClient in client.RelatedClientsClient)
            {
                var existingRelation = existingClient.RelatedClientsClient
                                       .Where(c => c.RelatedClientsId == relatedClient.RelatedClientsId)
                                       .SingleOrDefault();

                if (relatedClient.RelatedClientsId == 0)
                {
                    existingRelation = null;
                }

                if (existingRelation != null)
                {
                    _context.Entry(existingRelation).CurrentValues.SetValues(relatedClient);
                }
                else
                {
                    existingClient.RelatedClientsClient.Add(relatedClient);
                }
            }

            //_context.SaveChangesAsync();

            return(client);
        }