Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return inserted item's UUID back from Dapper/PostgreSQL

I have a model object like so in my ASP.Net Core 2.1 Web API Project:

public class Tenant
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

And am executing an insert into postgres like this:

public async Task<int> CreateItem(Tenant item)
{
    return await db.ExecuteAsync($@"INSERT INTO tenants (Name) VALUES (@Name)", item);
}

I need the Guid back, to drive the subsequent logic. It returns the affectedrows (1). My research shows a few tricks being used for getting back the autoincrement ID (like using 'MAX' and so forth).

Is there a way to do this, via dapper preferably? Or do I need to drop back to ADO.Net?

like image 600
Glinkot Avatar asked Sep 07 '18 03:09

Glinkot


People also ask

How do I perform an insert and return inserted identity with dapper?

string sql = "DECLARE @ID int; " + "INSERT INTO [MyTable] ([Stuff]) VALUES (@Stuff); " + "SELECT @ID = SCOPE_IDENTITY()"; var id = connection. Query<int>(sql, new { Stuff = mystuff}). First();

Can we use dapper with PostgreSQL?

Dapper is an open-source and micro ORM (object-relational mapping) product developed by the StackOverflow team. It is very lightweight and straightforward to use with a project. It supports PostgreSQL, MySQL, SQL Server, and other databases.


1 Answers

You should be able to use the RETURNING clause of the INSERT statement to have Postgres return the inserted id.

public async Task<Guid> CreateItem(Tenant item)
{
    return await db.ExecuteScalarAsync<Guid>($@"INSERT INTO tenants (Name) VALUES (@Name) RETURNING Id", item);
}
like image 160
Viktor Griph Avatar answered Oct 13 '22 02:10

Viktor Griph