There's a method on the Database helper: GetLastInsertId(). That will do what you want:
db.Execute("INSERT INTO table1 (col1, col2, col3) VALUES (@0,@1,@2)", param1, param2, param3);
var Id = db.GetLastInsertId();
It uses @@IDENTITY rather than SCOPE_IDENTITY because it has to support SQL Compact as well as SQL Server. So long as you don't have any triggers on your table, you should be fine with that.
If you do need to use SCOPE_IDENTITY for any compelling reason, you will have to use plain ADO.NET as in my article that sreejukg linked to.
fredd_and
Member
44 Points
46 Posts
SCOPE_IDENTITY
Feb 06, 2012 06:47 AM|LINK
Hi, i am trying to get the UserId of just inserted member from Userprofile table in webmatrix membership startersite template. Using C#
i try to use Scope Identity SQL in Account/register.cshtml, but dont know idea how to do it in webmatrix
any suggest how to do it? so i can take the UserId for new registed user.
thank you
sreejukg
All-Star
28177 Points
4214 Posts
Re: SCOPE_IDENTITY
Feb 06, 2012 06:54 AM|LINK
refer this
http://www.mikesdotnetting.com/Article/54/Getting-the-identity-of-the-most-recently-added-record
My Blog
fredd_and
Member
44 Points
46 Posts
Re: SCOPE_IDENTITY
Feb 06, 2012 07:42 AM|LINK
i read that blog before, and apply it to my asp.net web form,
in web matrix i can not get the value,
any sample in web matrix?
thank you
nilsan
All-Star
17538 Points
3824 Posts
Re: SCOPE_IDENTITY
Feb 06, 2012 07:54 AM|LINK
Please check this link
Blog | Get your forum question answered | Microsoft Community Contributor 2011
vijay_myl
Contributor
5070 Points
1068 Posts
Re: SCOPE_IDENTITY
Feb 06, 2012 08:09 AM|LINK
hi..
Refer the below link ..
http://www.dotnetcode.in/2012/01/identity-value-in-sql-or-usage-of.html
My .NET blog
Submit Article
Mikesdotnett...
All-Star
155597 Points
19981 Posts
Moderator
MVP
Re: SCOPE_IDENTITY
Feb 06, 2012 11:06 AM|LINK
There's a method on the Database helper: GetLastInsertId(). That will do what you want:
db.Execute("INSERT INTO table1 (col1, col2, col3) VALUES (@0,@1,@2)", param1, param2, param3); var Id = db.GetLastInsertId();It uses @@IDENTITY rather than SCOPE_IDENTITY because it has to support SQL Compact as well as SQL Server. So long as you don't have any triggers on your table, you should be fine with that.
If you do need to use SCOPE_IDENTITY for any compelling reason, you will have to use plain ADO.NET as in my article that sreejukg linked to.
Web Pages CMS | My Site | Twitter
fredd_and
Member
44 Points
46 Posts
Re: SCOPE_IDENTITY
Feb 07, 2012 04:30 AM|LINK
Thank you Mikes, i read this link before read your answer from there.
http://forums.asp.net/t/1752458.aspx/1?How+do+I+use+LAST_INSERT_ID+in+Webmatrix+to+connect+the+tables
i just realise there is "GetLastInsertedId" class for webmatrix.