2

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

Let's say if 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)
                  SELECT
                      @GUID, @FirstName, @LastName);

using (var oConn = CreateConnection())
{
    var test = oConn.Query<string>(query, new
            {
                GUID = Guid.NewGuid(), 
                "John", 
                "Doe"
            }).Single();
}

The error that I get is

Sequence contains no elements

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Bagzli
  • 6,254
  • 17
  • 80
  • 163
  • 1
    Store that `Guid.NewGuid()` to a variable , pass it for saving. You have the variable value available in your code. – Shyju Aug 25 '16 at 17:51

2 Answers2

3

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
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • 1
    When having your code create a GUID, you will run into collisions. You should trust your DB to create the identity. – Kevin B Burns Feb 21 '17 at 18:29
  • 7
    [I am ready to bet](http://stackoverflow.com/questions/1705008/simple-proof-that-guid-is-not-unique?noredirect=1&lq=1) – Shyju Feb 21 '17 at 18:45
0

Dapper Contrib needs a Auto Generated ID, It cannot be a GUID and you cannot pass a pre generated Guid