Is it possible to insert many rows in a single query using Dapper?

dapper mariadb mysql


Does StackExchange.Dapper support the following SQL syntax?

INSERT INTO MyTable (a, b, c)
  (1, 2, 3),
  (4, 5, 6),
  (7, 8, 9);

I've seen some examples where you can pass in a List to be inserted but the descriptions I've seen suggest it is just looping and doing multiple inserts.

My research suggests doing a single query with multiple rows in it is faster so I'm curious to know if Dapper supports this with a list or not.

4/17/2018 2:07:40 PM

Popular Answer

No it doesn't.

Actually, bulk insert is one of the most discussed issue. I never came across the solution you are looking for with Dapper.

One hack I can imagine (not sure; never tried) is to pass DynamicParameters replacing your actual values (1, 2, 3....). So your query becomes something like below:

INSERT INTO MyTable (a, b, c)
  (@1, @2, @3),
  (@4, @5, @6),
  (@7, @8, @9);

And, you pass in DynamicParameters something like below:

var param = new DynamicParameters();
param.Add("@1", ...);
param.Add("@2", ...);
param.Add("@3", ...);
param.Add("@4", ...);

As I said above, this is what I imagine; I have not tried it. Even if this works, this will not be a good solution as string building cost will be high and managing too many parameters will be tricky. Also, there is limitation on RDBMS side how many maximum parameters you can pass. So, I am not recommending this.

If number of records are not too much OR if performance is not that critical (still important; I agree), passing in the List to INSERT query (as you mentioned in question) works great. Wrapping Execute call in Transaction may help.

Otherwise, following solutions are generally recommended:

  1. Bypass Dapper; use ADO.NET.
  2. Use stored procedure with User Defined Table parameter.
  3. Passing Table Valued Parameters with Dapper
  4. Use some other tool like SqlBulkCopy, Dapper Plus, MicroOrm.Dapper.Repositories etc.
    I have never used those tools; so I am not aware about their performance or other drawbacks.
4/18/2018 2:09:08 PM

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow