When inserting, updating, or deleting a record, how to get the ID with Dapper?

asp.net asp.net-core c# dapper

Question

When I insert or update or delete an entity with Dapper, I need to return the id of entity.

I am using this code :

var role = await roleConnection.ExecuteAsync("UPDATE Role SET IsDelete = @isDelete, RoleName = @roleName, SecurityStamp = @securityStamp WHERE Role.Id = @id SELECT SELECT CAST(SCOPE_IDENTITY() AS INT)"
                     , new
                     {
                         isDelete = request.IsDelete = false,
                         roleName = request.RoleName,
                         securityStamp = Guid.NewGuid(),
                         id = request.Id
                     });

but it does not show me anything.

How can I do this?

1
1
10/19/2019 6:16:28 PM

Accepted Answer

Well, in the case of UPDATE or DELETE, you already must have the `id^, otherwise you couldn't be calling any of these methods - correct?

In the case of an INSERT, if your table is in SQL Server and has an INT IDENTITY column, you can use something like this:

INSERT INTO dbo.YourTable (list-of-columns)
OUTPUT Inserted.Id   -- or whatever your IDENTITY column is called
VALUES (list-of-values)

and then from your C# code, use cmd.ExecuteScalar() (or ExecuteScalarAsync, if your prefer) to run this and get back a single, atomic value (the newly created id value):

var result = cmd.ExecuteScalar(....);

if (result != null)
{
    int newId = Convert.ToInt32(result);
}
1
10/19/2019 6:22:51 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow