Dapper multiple insert records and return id

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 ); 
+8
dapper
source share

No one has answered this question yet.

See related questions:

148
Perform attachments and updates using Dapper
117
How to insert and return pasted identity using Dapper?
10
Dapper Bulk Insert Returns Serial Identifiers
10
Insert one of many objects using dapper
2
Dapper.NET ExecuteNonQuery requires the command to have a transaction
2
How to use Dapper for mass insertion with foreign keys?
one
How can I use Dapper with a SELECT stored procedure containing an INNER JOIN between two tables?
one
Insert multiple values ​​and return multiple values
0
Dapper 1.42 and Sybase.AdoNet45.AseClient do not insert string variables
0
Dapper class property names with Datatypes C # return

All Articles