I appreciated Dapper for replacing the EF6 we used.
One use case involves inserting multiple records into a table where we need to return an identifier column and another datetime column for the database.
To illustrate - consider the table
Create Table Demo ( Id int indentity(1,1) PRIMARY KEY, Name VARCHAR(10), WhenCreated DATETIME DEFAULT(GETDATE()) )
I know that I can insert several records using Connection.Execute - But this does not return me Id, Whencreated columns.
var connection = new SqlConnection(); var names = new []{ {Name = "Name1"}, {Name = "Name2"}}; connection.Execute("Insert into Demo(Name) values(@Name)", names );
To return the authentication data, I could use Connection.Query
var connection = new SqlConnection(); var demo = connection.Query<Demo>( @"Insert into Demo(Name) values(@Name); Select * from Demo Where Id = Scope_IDENTITY();", new {Name = "Name1"} );
But this can only be done for one record at a time, i.e. each record represents a single trip to the server, which is impossible.
Essentially, Iβm looking for a way to do this (this will not work - because Query does not take / do not display the collection) - that is, insert several records in one trip to the server and return identifiers (or even any other columns) for all inserted rows
var connection = new SqlConnection(); var names = new []{ {Name = "Name1"}, {Name = "Name2"}}; var demo = connection.Query<Demo>( @"Declare @Inserted Table (Id int); Insert into Demo(Name) OUTPUT Inserted.Id into @Inserted values(@Name); Select * from @Inserted", names );
dapper
user3595571
source share