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?
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();
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With