问题
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 ?
回答1:
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 await
s 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
来源:https://stackoverflow.com/questions/26279352/dapper-bulk-insert-of-new-items-and-get-back-new-ids