我正在开发一个使用 sql Server 数据库的应用程序。I 自动生成的主键的值,用于存储到数据集中。我正在使用下面的代码。但问题是我的主键列,即 ProdNum 是只读的。为此,它不允许设置该值。我怎样才能克服这个问题?
Private Sub OnRowUpdated(ByVal sender As Object, ByVal args As Data.OleDb.OleDbRowUpdatedEventArgs)
' Include a variable and a command to retrieve the identity value from the Access database.
Dim newID As Integer = 0
Dim idCMD As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT @@IDENTITY", args.Command.Connection(), args.Command.Transaction)
If args.StatementType = StatementType.Insert Then
' Retrieve the identity value and store it in the ProductIDNum column.
newID = CInt(idCMD.ExecuteScalar())
' place in the identity column of the local table in the dataset
'args.Row("ProdNum") = newID
End If
End Sub
我不确定您是否可以使用OleDb
执行此操作(您不能用于 Access,但这是一个不同的 OLE DB 提供程序(,但如果您使用 SqlClient
则无需处理任何事件,因为您只需在适配器InsertCommand
的CommandText
将SELECT
附加到INSERT
上, 例如
INSERT INTO Thing (Name, Description) VALUES (@Name, @Description);
SELECT ThingId = SCOPE_IDENTITY();
这一直对我有用。