0

I have a collection of rental properties which each have a bunch of images attached to them (as a child object). I am using the EF 4.0 with a sql ce database and I need to be able to remove all properties and images from the database. Here is the code I am using:

    private void SaveProperty()
    {
        try
        {
            if (PropertyList != null)
            {
                //Purge old database      
                IList<Property> ClearList = new List<Property>(from property in entities.Properties.Include("Images") select property);
                foreach (Property a in ClearList)
                {
                    if (a != null)
                    {
                        if (a.Images.Count != 0)
                        {
                            Property property = entities.Properties.FirstOrDefault();

                            while (property.Images.Count > 0)
                            {
                                var image = property.Images.First();
                                property.Images.Remove(image);
                                entities.DeleteObject(image);
                            }

                            entities.SaveChanges();
                        }
                        entities.DeleteObject(a);
                        entities.SaveChanges();
                    }
                }


                foreach(Property p in PropertyList.ToList())
                {                        
                    //Store sort (current position in list)
                    p.Sort = PropertyList.IndexOf(p);
                    entities.AddToProperties(p);
                    entities.SaveChanges();
                }
            }
        }

        catch (Exception ex)
        {
            System.Windows.MessageBox.Show(ex.Message);
        }
    }

I get this error: The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

It links to the SaveChanges() command straight after the Image foreach loop. Any ideas why I get this?

EDIT:

This is the old code that worked fine under my old program structure (without mvvm).

        private void DeleteProperty()
    {
        if (buttonPres.IsChecked == false)
        {
            //Perform parts of DeleteImage() method to remove any references to images (ensures no FK errors)
            Property p = this.DataContext as Property;
            if (p == null) { return; }

            MessageBoxResult result = System.Windows.MessageBox.Show(string.Format("Are you sure you want to delete property '{0}'?\nThis action cannot be undone.", p.SaleTitle), "Confirm Delete", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.Yes)
                try
                {
                    int max = listBoxImages.Items.Count;
                    for (int i = 0; i < max; i++)
                    {
                        Image img = (Image)listBoxImages.Items[0];
                        entities.DeleteObject(img);
                        entities.SaveChanges();
                    }

                    entities.DeleteObject(p);
                    entities.SaveChanges();
                    BindData();
                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show(ex.Message, "Exception", MessageBoxButton.OK, MessageBoxImage.Error);
                }
        }
    }

Note: Binddata() simply refreshes the listbox of properties.

randomalbumtitle
  • 151
  • 3
  • 15
  • can you add codes of your entity classes here..? – Jayantha Lal Sirisena Apr 18 '12 at 09:28
  • 1
    possible duplicate of [The relationship could not be changed because one or more of the foreign-key properties is non-nullable](http://stackoverflow.com/questions/5538974/the-relationship-could-not-be-changed-because-one-or-more-of-the-foreign-key-pro) – Jayantha Lal Sirisena Apr 18 '12 at 09:33
  • Its just two simple entity classes, one for property and one for image. A property can have 1 * many images. Each image only one property. To create a property its simply entities.property.add(new property); For the images I do CurrentProperty.Images.Add(new image). – randomalbumtitle Apr 18 '12 at 10:32

1 Answers1

0

My bet is to remove the save changes after deleting the images, if this relationship is 1-many you will be saving changes to a state that violates this relationship

try:

       //Purge old database                  
    foreach (Property a in entities.Properties)
    {
        if (a != null)
        {
            if (a.Images != null)
            {
                foreach (Image i in a.Images)
                {
                    entities.Images.DeleteObject(i);
                }
            }
            entities.Properties.DeleteObject(a);
        }

    }
    entities.SaveChanges();
undefined
  • 33,537
  • 22
  • 129
  • 198
  • The images property can be set to null so I don't think this is the problem (ie: the relationship is that the property can have many images or none). Sorry that I didnt make this clear before. – randomalbumtitle Apr 19 '12 at 06:00
  • This is my code for the entire method. Basically I am communicating with the database from my viewmodel as the program is not large enough to warrant a separate datalayer. This command simply aims to delete all existing data on the database and repopulate it with the data from the observablecollection. It fails at the same point when I add an image to a property, save it to the database, but then later delete that property and save the changes. – randomalbumtitle Apr 20 '12 at 02:07
  • I have also added code for my method that performed the same operation under my old model (not using mvvm). – randomalbumtitle Apr 20 '12 at 02:08