Home
Manage Your Code
Snippet: Return new identity from Strongly Typed Dataset DataTable.Insert method (C#)
Title: Return new identity from Strongly Typed Dataset DataTable.Insert method Language: C#
Description: Return new identity from Strongly Typed Dataset DataTable.Insert method Views: 263
Author: Brendan Le Date Added: 10/8/2008
Copy Code  
1
2
3Datasets are pretty good at auto generating stored procedures and wrapping c# code around them for you.
4
5However with the insert method you often want to do something with the object that you have just inserted.
6
7Fortunately there is an easy way to get the Sproc and the c# method to return a reference to the object.
8
9Firstly edit your insert stored procedure adding a @return parameter and a line after the insert to set this to a suitable value.
10
11The exmaple below assumes that you are using bigint identity fields.
12
13ALTER PROCEDURE dbo.insMyRow
14(
15    @Description varchar(500),
16    @Return bigint output
17)
18AS
19    SET NOCOUNT OFF;
20INSERT INTO [myTable] ([Description]) VALUES (@Description);
21    
22SET @Return = SCOPE_IDENTITY()
23
24Note that SCOPE_IDENTITY() is similar to @@IDENTITY except its scope is limited to the current command and so improves scalability.
25
26Now when you save the Dataset you see that the insert method takes two parameters, the second being a nullable long.
27
28My first thought was that Datasets should be the end of editing stored procedures but I am still impressed that the c# method declaration changes accordingly.
29
30You can call the updated method in the following way.
31
32long? objId=null;
33
34myTableAdapter d =new myTableAdapter();
35
36d.Insert("Descriptive text", ref objId);
37
38the long? just means nullable long.
39
40After filling the table you can now use the FindByxxxID functions of the DataTable to return the DataRow object.
41