EF 4.3.1 で entities.savechanges() を呼び出すとエラーが発生します。私のデータベースは sql ce v4 ストアで、mvvm パターンでコーディングしています。監視可能なコレクションに送信して変更などを行うコンテキストのローカル バージョンがあります。これは正常に機能し、データベースに行が存在しないときに savechanges() を呼び出すと、オブジェクトは正常に保持されます。アプリケーションをリロードすると、オブジェクトがリストボックスに表示されますが、別のオブジェクトを追加して savechanges() を呼び出すと、一意のインデックスに重複する値を挿入できないというエラーが表示されます。
私の理解では、コンテキストがエンティティをデータストアに保存しようとしていることを意味しますが、元のオブジェクトと新しいオブジェクトを追加しているようです。彼らの状態は変わらないので、彼らを放っておくと思いました。
private void Load()
{
entities.Properties.Include("Images").Load();
PropertyList = new ObservableCollection<Property>();
PropertyList = entities.Properties.Local;
//Sort the list (based on previous session stored in database)
var sortList = PropertyList.OrderBy(x => x.Sort).ToList();
PropertyList.Clear();
sortList.ForEach(PropertyList.Add);
propertyView = CollectionViewSource.GetDefaultView(PropertyList);
if (propertyView != null) propertyView.CurrentChanged += new System.EventHandler(propertyView_CurrentChanged);
private void NewProperty()
{
try
{
if (PropertyList != null)
{
Property p = new Property()
{
ID = Guid.NewGuid(),
AgentName = "Firstname Lastname",
Address = "00 Blank Street",
AuctioneerName = "Firstname Lastname",
SaleTitle = "Insert a sales title",
Price = 0,
NextBid = 0,
CurrentImage = null,
Status = "Auction Pending",
QuadVis = false,
StatVis = false, //Pause button visibility
Sort = PropertyList.Count + 1,
};
PropertyList.Add(p);
SaveProperties();
}
private void SaveProperties()
{
try
{
foreach (var image in entities.Images.Local.ToList())
{
if (image.Property == null)
entities.Images.Remove(image);
}
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
entities.SaveChanges();
}