这个问题很难追查。我为DataGrid使用了ObservableCollection:
可观察的收藏品制作
_claims = new ObservableCollection<Claim>(
_context.Claims.Include("Inventory").Where(c => c.Id == claimID));
...
_claimInventoryViewSource = ((CollectionViewSource)(this.FindResource("claimViewSource")));
_claimInventoryViewSource.Source = _claims;
我可以根据需要删除DataGrid中的任意数量的记录而不会出现问题(实际上是这样),但是在过滤(下面的代码)之后,然后删除项目时,集合会发生一些事情。当我删除另一条记录时,我收到此错误:
数据库的更改已成功提交,但出现错误 更新对象上下文时发生。 ObjectContext可能是 处于不一致的状态。内部异常消息:参考 发生完整性约束违规:属性值 定义参照约束之间不一致 关系中的主体和依赖对象。
删除代码:
Inventory inventoryItem = inventoryDataGrid.SelectedItem as Inventory;
Int32 selectedIndex = inventoryDataGrid.SelectedIndex;
if (selectedIndex == inventoryDataGrid.Items.Count - 1)
selectedIndex--;
_context.Inventory.DeleteObject(inventoryItem);
过滤代码:
private void inventoryGrid_Filter(object sender, System.Windows.Data.FilterEventArgs e)
{
if (e.Item is Inventory)
e.Accepted = (e.Item as Inventory).Description != null && (e.Item as Inventory).Description.ToUpper().Contains(txtFindItem.Text.ToUpper())
|| (e.Item as Inventory).Source != null && (e.Item as Inventory).Source.ToUpper().Contains(txtFindItem.Text.ToUpper())
else
e.Accepted = true;
}
private void RefreshList()
{
if (inventoryDataGrid.Items is CollectionView)
{
CollectionViewSource csv = (CollectionViewSource)FindResource("claimInventoryViewSource");
if (csv != null)
csv.View.Refresh();
}
}
希望这很清楚,先谢谢!