c# - Accessing rows PK after Insert (SqlDataSource) -
i need able primary key of nserted row in c#, , far i'm unsure how. i've put select scope_identity() sql query, how access sqldatasource_inserting method, can store in auditing table? in method how access parameters (e.command.parameters)
edit:
my parameters stored in asp.net file (some extracts):
insertcommand="insert [nominalcode] ([vaxcode], [reference], [costcentre], [department], [reportingcategory]) values (@vaxcode, @reference, @costcentre, @department, @reportingcategory)" <insertparameters> <asp:controlparameter controlid="detailsview1" name="vaxcode" propertyname="selectedvalue" /> <asp:controlparameter controlid="detailsview1" name="reference" propertyname="selectedvalue" /> <asp:controlparameter controlid="detailsview1" name="costcentre" propertyname="selectedvalue" /> <asp:controlparameter controlid="detailsview1" name="department" propertyname="selectedvalue" /> <asp:controlparameter controlid="detailsview1" name="reportingcategory" propertyname="selectedvalue" /> </insertparameters>
and fill parameters in c# codebehind
command.parameters.addwithvalue("@source", "nominal"); command.parameters.addwithvalue("@action", "insert"); command.parameters.addwithvalue("@item", fields); command.parameters.addwithvalue("@userid", name); command.parameters.addwithvalue("@timestamp", datetime.now);
thanks
you can access via command parameters adding new 1 direction of output, (or can use returnvalue if you're not returning result, rows affected).
ie. add these 3 rows end of parameters list
sqlparameters pkey = new sqlparameters("@pkey", system.data.sqldbtype.int); pkey.direction = output; command.parameters.add(pkey);
then @ end of sql, set parameter primary key value so:
set @pkey = scope_identity();
ie.
insertcommand="insert [nominalcode] ([vaxcode], [reference], [costcentre], [department], [reportingcategory]) values (@vaxcode, @reference, @costcentre, @department, @reportingcategory); set @pkey = scope_identity()"
then read after you've executed command:
int primarykey = (int)pkey.value;
simples!
another way auditing have stored proc perform audit capture directly, ensure consistency , save doing in apps down preference , system design.
Comments
Post a Comment