私は、それぞれに(子オブジェクトとして)たくさんの画像が添付されている賃貸物件のコレクションを持っています。SQL ce データベースで EF 4.0 を使用しており、データベースからすべてのプロパティと画像を削除できるようにする必要があります。私が使用しているコードは次のとおりです。
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);
}
}
次のエラーが表示されます: The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. リレーションシップに変更が加えられると、関連する外部キー プロパティが null 値に設定されます。外部キーが null 値をサポートしていない場合は、新しい関係を定義するか、外部キー プロパティに別の非 null 値を割り当てるか、関連のないオブジェクトを削除する必要があります。
これは、Image foreach ループの直後に SaveChanges() コマンドにリンクしています。なぜ私はこれを得るのですか?
編集:
これは、私の古いプログラム構造 (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);
}
}
}
注: Binddata() は、単にプロパティのリストボックスを更新します。