Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to SQL - How to find the value of the IDENTITY column after InsertOnSubmit()

I am using LINQ to SQL to insert simple data into a table WITHOUT a stored procedure. The table has a Primary Key ID column, which is set as an IDENTITY column in both SQL Server and in my DBML.

First I call InsertOnSubmit(); with data for a single row, and then I call SubmitChanges(); to commit the row to the db. But I think there must be a simple way to then retrieve the row's IDENTITY column value of the newly inserted row. I don't wish to provide the IDENTITY column value to the db, I want it to generate one for me.

How is this best handled?

like image 240
Ash Machine Avatar asked Apr 30 '09 19:04

Ash Machine


People also ask

How do I find the identity column value?

We use system function @@IDENTITY to return the maximum used IDENTITY value in a table for the IDENTITY column under the current session. Once we insert a row in a table, the @@IDENTITY function column gives the IDENTITY value generated by the statement.

How do I find the next value of an identity in SQL Server?

You cannot reliably find out the next identity value - until you've actually inserted a new row into the table. Stop trying - you won't succeed - just accept the fact you cannot know the identity value before the row is actually inserted into the table and SQL Server has assigned the value.


1 Answers

here is a simple code snippet

            Dim odb As New DataClassesDataContext
            Dim tst As New test
            tst.name = "abcd"
            odb.tests.InsertOnSubmit(tst)
            odb.SubmitChanges()
            Response.Write("id:" + tst.id.ToString)

so, basically the object you used in InsertOnSubmit will get the identity field populated after the record has been created in the database

like image 54
Vikram Avatar answered Sep 20 '22 10:09

Vikram