Search code examples
sql-serverasp.net-mvcvisual-studio-2012asp.net-mvc-5

Using Dapper Dot Net get last inserted id


I am using Microsoft Visual Studio Express 2012 for Web to develop the MVC5 application. I want to get last inserted ID by using Dapper dot net. I got solutions here but they are working on SQL Server 2012 (Management Studio) but when I run the query in code then returning value is wrong. Here are pieces of code that I have tried already to get last inserted ID

SqlConnection _db = new SqlConnection("String");

        string query_1 = @"DECLARE @InsertedRows AS TABLE (user_id int);Insert into users (stuff) OUTPUT Inserted.user_id INTO @InsertedRows values(@stuff); SELECT user_id FROM @InsertedRows";
        string query_2 = @"Insert into users (stuff) OUTPUT Inserted.user_id values(@stuff);";
        string query_3 = @"Insert into users (stuff) values(@stuff); SELECT SCOPE_IDENTITY()";

        1. var id = _db.Query<int>(query_x, new { stuff = @stuff });
        2. var id = _db.Execute(query_x, new { stuff = @stuff });

but the value of ID in both cases is 1 but not actual result. but when I run the same query on SQL management Studio then all things okay. Please help to fix this problem.


Solution

  • Okay I am going to answer my own asked question I got answer after some other search in Dapper we have a Extension Method .Single() that will return the value of Selectd value newly added i.e.

    var id = _db.Query<int>(query_x, new { stuff = @stuff }).Single();
    

    in my case it will return the value of newly added primary key value. I just add the .Single() function to get newly added value.