Can Dapper batch a set of stored proc calls? I see it supports Multiple Results in the documentation but I'm not sure if you can execute multiple stored proc calls using Dapper.
Using stored procedures with Dapper can be a great way to take advantage of the strengths of the database while reducing complexity of your code.
Multiple Result Sets Using Dappervar results = await connection. QueryMultipleAsync(sql,new { id = 1 }); var people = results. Read<Person>(). ToList(); var food = results.
We can execute this stored procedure using Dapper with the following piece of C# code: using var con = new SqlConnection("<Your connectionstring>"); con. Open(); var sql = "EXEC GetEntity @Id"; var values = new { Id = 0 }; var getEntityResult = con. Query(sql, values).
JOIN approach with Dapper. The correct solution is to query the Customer table and create the single Customer object and then query the Order table, create the Order objects and the link them to the created customer.
Dapper supports batching commands for stored procs:
connection.Execute("create table #t (i int)");
connection.Execute("create proc #spInsert @i int as insert #t values (@i)");
connection.Execute("#spInsert", new[] { new { i = 1 }, new {i = 2}, new {i = 3} },
commandType: CommandType.StoredProcedure);
var nums = connection.Query<int>("select * from #t order by i").ToList();
nums[0].IsEqualTo(1);
nums[1].IsEqualTo(2);
nums[2].IsEqualTo(3);
The code above reuses the IDbCommand with the text #spInsert
, 3 times. This makes batching inserts a bit more efficient.
In general if you worry about perf at this level you would wrap the batch call in a transaction.
Additionally Dapper supports whatever batch you decide to send it:
connection.Execute(@"
exec #spInsert @i = @one
exec #spInsert @i = @two
exec #spInsert @i = @three",
new { one = 1, two = 2, three = 3 });
Which would cause three rows to be inserted.
Further more, if #spInsert
returned a result set you could use QueryMultiple
to execute the batch which would give you 3 record sets to iterate through.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With