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

这一生的挚爱 提交于 2019-12-12 09:57:18

问题


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 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



来源:https://stackoverflow.com/questions/26279352/dapper-bulk-insert-of-new-items-and-get-back-new-ids

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!