Bagzli Bagzli - 8 months ago 29
C# Question

Insert Guid and retreive value with dapper

I am trying to insert a record into my database and retrieve the GUID record it just added in.

So if lets say I have a table with 3 columns, GUID, FirstName, LastName. I need to insert a new record and then get back the GUID that was just generated. The problem is that first and last name are duplicated, often. I am not quite sure how to accomplish

here is what I tried, I know the below won't work as I am not really telling it which column to select back and I'm not sure how to tell it:

var query = @"INSERT INTO
MyTable(GUID, FirstName, LastName)
using (var oConn = CreateConnection())
var test = oConn.Query<string>(query, new
GUID = Guid.NewGuid(),

The error that I get is

Sequence contains no elements


If you want only the Guid which you inserted, Why not store it in a local variable in your code and use that as needed ?

I also see some errors in your code. The below code is corrected and should work.

var guid = Guid.NewGuid();
var query = @"INSERT INTO
              MyTable (GUID, FirstName, LastName) values ( @GUID, @FirstName,@LastName);";
using (var conn =  CreateConnection())
    conn.Execute(query, new {  @GUID = guid, @FirstName= "John", @LastName= "Scott" });
// You can use the value in guid variable now. It will be Id you inserted just now