Search code examples
c#sql-server.net-coredappersqlconnection

Get inserted ID back from SqlConnection.Execute stored procedure


I'm inserting data into my database like so:

using (IDbConnection conn = new SqlConnection(connectionString))
{
    conn.Execute(storedProcedure, parameters, commandType: CommandType.StoredProcedure);
}

I've added select SCOPE_IDENTITY(); to my stored procedures so now the id is returned from the query. How can I access it?


Solution

  • This looks like Dapper, yes? So: instead of using Execute, use QuerySingle<T> for whatever T you are selecting - presumably int or long:

    var id = conn.QuerySingle<int>(storedProcedure, parameters,
        commandType: CommandType.StoredProcedure);
    

    As a side note: you may find it easier to use the OUTPUT clause during the INSERT.