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.