c# - 从 Dapper/PostgreSQL 返回插入项的 UUID

标签 c# postgresql asp.net-core dapper

我的 ASP.Net Core 2.1 Web API 项目中有一个模型对象:

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

然后像这样在 postgres 中执行插入操作:

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

我需要返回 Guid,以驱动后续逻辑。它返回受影响的行 (1)。我的研究显示了一些用于取回自动增量 ID 的技巧(例如使用“MAX”等)。

有没有办法做到这一点,最好是通过 dapper?还是我需要返回到 ADO.Net?

最佳答案

您应该能够使用 INSERT 语句的 RETURNING 子句让 Postgres 返回插入的 ID。

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

关于c# - 从 Dapper/PostgreSQL 返回插入项的 UUID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52215029/

相关文章:

c# - linq to sql c# : SubmitChanges() not updating the database

postgresql - Postgres : make repeated subqueries more efficient?

c# - dotnet core 1.1.1、mvc 1.1.2 中未调用模型绑定(bind)程序提供程序

javascript - 将表中的数据绑定(bind)到 JavaScript 数组的最有效方法?

c# - C# 中带有 FileSystemWatcher 的 Windows 服务

c# - Unity注册抽象类和解析派生类

c# - 在 C# 中编写当单击消息框上的 X 时的代码

sql - 如何在 Postgres 中使用 json 键连接 2 个表?

javascript - Sequelize : TypeError: User. hasMany不是函数

c# - 如何在 ASP. NET Core 中使用 jquery