Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Dapper batch a set of stored proc calls?

Tags:

c#

.net

dapper

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.

like image 933
Kyle Nunery Avatar asked Aug 18 '11 14:08

Kyle Nunery


People also ask

Does Dapper support stored procedures?

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.

How do you get multiple results in Dapper?

Multiple Result Sets Using Dappervar results = await connection. QueryMultipleAsync(sql,new { id = 1 }); var people = results. Read<Person>(). ToList(); var food = results.

How do you call a stored procedure using Dapper?

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

Which Dapper method should be used when retrieving multiple resultsets?

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.


1 Answers

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.

like image 121
Sam Saffron Avatar answered Oct 22 '22 18:10

Sam Saffron