Dapper - Bulk insert of new items and get back new IDs

bulkinsert c#-4.0 dapper dapper-extensions sql

Question

I am using dapper to add multiple new students in one db hit using this method:

db.ExecuteAsync(@"INSERT Student(Name,Age) values (@Name,@Age)", 
  students.Select(s => new { Name = s.Name, Age = s.Age })
);

But the problem I don't have the new ids.

Can I make one db hit and still some how get the new ids ?
And if not, what is the most efficient way of performing such bulk insert ?

Expert Answer

That is not a bulk insert; it is basically just shorthand that unrolls the loop; although interestingly (perhaps) it is possible to ask it to pipeline that sequence if "MARS" is enabled on your connection. Without the pipeline, it is basically shorthand for:

foreach(var obj in students.Select(s => new { Name = s.Name, Age = s.Age }))
{
    await db.ExecuteAsync(@"INSERT Student(Name,Age) values (@Name,@Age)", obj);
}

in which case, you might as well use Query or ExecuteScalar to fetch the SCOPE_IDENTITY().

With the pipeline, it is more subtle; it does the same thing, but with multiple outstanding commands at a time (it only awaits when the backlog is full, or when all of the commands have been issued).

Bulk insert does not return ids. You could consider using a table valued parameter and using INSERT with the OUTPUT clause to insert an entire DataTable of data at a time (getting the identities in the process), but on the negative side: it does involve using DataTable ;p




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why