Search code examples
.netsqlvb.netado.netstrongly-typed-dataset

How do I get the primary key of the row I just inserted into a typed dataset in .net?


I have some VB.net code that inserts data into my SQL database using a typed dataset as follows:

dim usersTa As New authorizedUsersTableAdapters.Authorized_UsersTableAdapter usersTa.Connection = New Data.SqlClient.SqlConnection(MY_CONNECTION_STRING) usersTa.Insert(first_name, last_name)

In the database, there is a primary key by which I identify the rows. What is the most efficient way to find out the primary key of the row that I just inserted when I run this code?


Solution

  • I assume you are executing some kind of SQL in the Authorized_UsersTableAdapter.Insert() method.

    In order to return the identifier you use SCOPE_IDENTITY().

    Example if your identifier is an Int.

    Dim conn As SqlConnection = ...
    Dim cmd As New SqlCommand(INSERT INTO T (Name) VALUES('Test')" & ChrW(13) & ChrW(10) & "SELECT SCOPE_IDENTITY() As TheId", conn)
    Dim tId As Integer = CInt(cmd.ExecuteScalar)