«

Using Dapper to Get Generated Id From Insert Query

I’ve been using [Dapper](“https://github.com/StackExchange/dapper-dot-net") as my ORM of choice for my personal .NET projects for a while now and wanted to document how you can return an generated id (primary key) from your Insert SQL statement.

A small example from the project I’m working on right now

using (var conn = new NpgsqlConnection(_optionsAccessor.DatabaseConnectionString))
{
    var guid = conn.Query<Guid>("INSERT INTO systems (name, description) VALUES (@Name, @Description) RETURNING id", new { Name = name, Description = description}).Single();

    return guid;
}

This works very much just like a normal query, just tell the query function what type you’re expecting back and by adding the Single function at the end it will return the only element in the enumerable (or throw an exception).