I am trying to complete a seemingly simple task that has turned into a several hour adventure: Getting @@Identity from TableAdapter.Insert().
The real answer:
Get identity from tableadapter insert function
I keep getting questions about this issue very often and never found time to write it down.
Well, problem is following: you have table with primary key with int type defined as Identity and after insert you need to know PK value of newly inserted row. Steps for accomplishing to do this are following:
use wizard to add new insert query (let's call it InsertQuery) in the body of query just add SELECT SCOPE_IDENTITY() at the bottom after saving this query, change ExecuteMode property of this query from NonQuery to Scalar in your code write following (ta is TableAdapter instance) :
int id; try { id = Convert.toInt32(ta.InsertQuery(firstName, lastName, description)); } catch (SQLException ex) { //... } finally { //... }Make money with this! :) Posted 12th March 2009 by Draško Sarić
From: http://quickdeveloperstips.blogspot.nl/2009/03/get-identity-from-tableadapter-insert.html
Notes:
Setting the ExecutMode to Scalar is possible via the Properties of your generated Insert Query. (press F4).
In my version (Visual Studio 2010 SP1 ) the select statement was generated automatically.