Using Dapper Dot Net get last inserted id

11,314

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.

Share:
11,314
Muhammad Usman
Author by

Muhammad Usman

"The three chief virtues of a programmer are: Laziness, Impatience and Hubris." Laziness: I'm too lazy to do the same task repeatedly so write scripts to do that task for me. This makes people think I am intelligent. Impatience: I'm too impatient to wait for my code to run so rewrite the code to improve performance. This makes people think I am a good programmer. Hubris: When someone asks if I can do something I just say Yes, then go find out how to do it (Google!). This makes people think I can do anything. Ultimately, it means I can make a career out of being Lazy, Impatient, and Hubristic. Email : [email protected] SoReadyToHelp

Updated on June 04, 2022

Comments

  • Muhammad Usman
    Muhammad Usman almost 2 years

    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.