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

asp.net asp.net-core c# dapper

Question

I need to return the entity's data when using Dapper to insert, edit, or remove an entity.id of being.

Using this code, I

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 nothing is revealed to me.

How can I go about this?

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

Accepted Answer

Well, let's say thatUPDATE or DELETE Since you are calling any of these methods, you must already have the "id," right?

If there is anINSERT , if your SQL Server table has anINT IDENTITY column, use something like to this:

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

after which, in your C# code, utilizecmd.ExecuteScalar() (or ExecuteScalarAsync , if you like) to do this and get a solitary, atomic value (the freshly generatedid 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