我在 Linq to SQL 插入之间使用 ExecuteCommand 删除了一条记录,如下所示。
在 SubmitChanges 的最后一次调用中,我收到以下错误:
无法使用已在使用的密钥添加实体。
如果我使用Linq to SQL进行删除,我没有问题,但是ExecuteCommand
是一个发布的代码,所以我不能改变它。
我应该如何再次插入已删除的记录?
下面是我的代码:
Using db = New SomeDataContext(...)
db.Connection.Open()
db.Transaction = db.Connection.BeginTransaction()
' Insert
db.Student.InsertOnSubmit(New Student() With {.Id = 1, .Name = "a"})
db.SubmitChanges()
' Delete(ExecuteCommand)
db.ExecuteCommand("delete from Student where Id = 1")
db.SubmitChanges()
'' Delete(Linq to SQL)
'db.Student.DeleteOnSubmit(db.Student.Single(Function(m) m.Id = 1))
'db.SubmitChanges()
' Insert
db.Student.InsertOnSubmit(New Student() With {.Id = 1, .Name = "a"})
db.SubmitChanges()
End Using
我正在使用具有 SQL Server 访问权限的 Visual Studio 2013。