Search code examples
c#.netsql-serverdapper

How to get the value I entered in SQL


I am using the following query to store values ​​in a table:

INSERT INTO [dbo].[TB_Templates] ([DescTemplate], [Template], [User])
VALUES ('teste', 'teste', 'teste')

The table that stores the values ​​has the following columns:

[IDTemplate] [int] IDENTITY(1,1) NOT NULL
[DescTemplate] [varchar](255) NOT NULL
[Template] [varchar](max) NOT NULL
[User] [varchar](255) NOT NULL

After I store this value, I need to know the ID that was created with the row that I inserted to work with the value in my C# Web API.

Is there any way for me to know which IDTemplate was created?


Solution

  • From your service method return integer for the row you just added.

    return connection.QueryFirst<int>(
        @"INSERT INTO [dbo].[TB_Templates] ([DescTemplate] ,[Template] ,[User])
          VALUES (@descTemplate, @template, @user);
    
          SELECT SCOPE_IDENTITY();",
        new { descTemplate,  template, user }
    );