How do I get the primary key of a row I just inserted into a typed dataset in .net?
I have VB.net code that inserts data into my SQL database using a typed dataset like this:
dim usersTa As new authorizedUsersTableAdapters.Authorized_UsersTableAdapter usersTa.Connection = New data. SqlClient.SqlConnection (MY_CONNECTION_STRING) usersTa.Insert (first_name, last_name)
The database has a primary key by which I identify rows. What is the most efficient way to find out the primary key of the row I just inserted when I run this code?
a source to share
I am assuming you are executing some kind of SQL in a method Authorized_UsersTableAdapter.Insert()
.
To return the id you use SCOPE_IDENTITY()
.
Example if your id is 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)
a source to share
There's a library in there, Kailua - Forgotten Methods in the ADO.NET API. which provides this and additional metadata for the top 5 vendors. This information is vendor specific.
Wrap your connection in net.windward.utils.ado.WrCommand
and use the function ExecuteInsert
.
a source to share
You need to tell your desktop table adapter to update the data table after an update / insert operation. Here's how you can do it.
-
Open TableAdapter properties - > Default Select Query -> Advnaced options . and select the Refresh Data Table check box . Save the adapter now. Now, when you call update on table-adapter, the data table will be updated [updated] after the update / insert operation and will display the latest values ββfrom the database table. if the primary key or any coloumn is set to auto-increment, the data table will have the last update of the last value.
-
Now you can call the update as TableAdapterObj.Update (ds.dataTable);
-
Read the latest values ββfrom the DataTable columns (ds.dataTable) and assign the appropriate values ββto the child table before updating / inserting . This will work exactly the way you want.
a source to share