public static CustomerAddress CreateOrUpdateCustomerAddress(CustomerContact contact, AddressModel addressModel) { var customerAddress = GetAddress(contact, addressModel.AddressId); var isNew = customerAddress == null; IEnumerable <PrimaryKeyId> existingId = contact.ContactAddresses.Select(a => a.AddressId).ToList(); if (isNew) { customerAddress = CustomerAddress.CreateInstance(); } customerAddress = addressModel.ConvertToCustomerAddress(customerAddress); if (isNew) { contact.AddContactAddress(customerAddress); } else { contact.UpdateContactAddress(customerAddress); } contact.SaveChanges(); if (isNew) { customerAddress.AddressId = contact.ContactAddresses .Where(a => !existingId.Contains(a.AddressId)) .Select(a => a.AddressId) .Single(); addressModel.AddressId = customerAddress.AddressId; } return(customerAddress); }