删除其他程序中的记录后出现DuplicateKeyException

时间:2016-07-20 12:28:02

标签: c# sql-server linq

我遇到了C#和Linq的问题。如果我创建一个记录,在另一个程序中删除它(当C#程序仍然打开时),并且想要在C#中重新创建记录,我得到一个DuplicateKeyException,尽管该表在物理上是空的。刷新表没有帮助。我猜有一些索引缓存受到影响。

我正在使用MS SQL Server 2012。

第1步:在表格中添加内容。

  CUSTOMERS test2 = new CUSTOMERS();
  test2.CUSTOMERID = 10;
  test2.FOO = 1;
  test2.BAR = 1;
  CoreDB.CUSTOMERS.InsertOnSubmit(test2);
  CoreDB.SubmitChanges();

步骤2:在不同的程序(例如SQL Explorer)中,删除记录。

第3步:刷新表并检查记录数。

CoreDB.Refresh(RefreshMode.OverwriteCurrentValues, CoreDB.CUSTOMERS);
if (CoreDB.CUSTOMERS.Count(ds=> ds.CUSTOMERID == 10 && ds.FOO == 1 && ds.BAR == 1) == 0) {
    MessageBox.Show("Good! Record not available anymore"); // <-- will be shown
}

第4步:尝试再次插入记录。它会失败。

  CUSTOMERS test1 = new CUSTOMERS();
  test1.CUSTOMERID = 10;
  test1.FOO = 1;
  test1.BAR = 1;
  CoreDB.CUSTOMERS.InsertOnSubmit(test1);
  CoreDB.SubmitChanges(); // <-- DuplicateKeyException

仅当我关闭连接并重新打开它时才有效。如果我只是刷新表,计数将变为0,但是会有索引冲突,尽管表是物理上的空。

如果不始终打开​​/关闭连接,我该怎么做才能使它工作?

1 个答案:

答案 0 :(得分:0)

在进行任何更新之前,您是否尝试重新初始化DbContext

第1步

开始
CoreDB = new YourContextHere(); //re-initialize context to clear memory changes
CUSTOMERS test2 = new CUSTOMERS();
test2.CUSTOMERID = 10;
test2.FOO = 1;
test2.BAR = 1;
CoreDB.CUSTOMERS.InsertOnSubmit(test2);
CoreDB.SubmitChanges();

然后执行第2步第3步

对于第4步,请对步骤1执行相同的操作

CoreDB = new YourContextHere(); //re-initialize context to clear memory changes
CUSTOMERS test1 = new CUSTOMERS();
test1.CUSTOMERID = 10;
test1.FOO = 1;
test1.BAR = 1;
CoreDB.CUSTOMERS.InsertOnSubmit(test1);
CoreDB.SubmitChanges(); 

SubmitChanges 不回滚在内存中完成的事务/操作,并且不会被当前的数据库上下文跟踪( CoreDB ),内存中的更改将需要手动回滚在每次需要对数据库进行更改时重新初始化

,在上下文中