Performing Operations Against Multiple Sets of Input

Download dapper eBook

Example

Sometimes, you want to do the same thing multiple times. Dapper supports this on the Execute method if the outermost parameter (which is usually a single anonymous type, or a domain model instance) is actually provided as an IEnumerable sequence. For example:

Order[] orders = ...
// update the totals
connection.Execute("update Orders set Total=@Total where Id=@Id", orders);

Here, dapper is just doing a simple loop on our data, essentially the same as if we had done:

Order[] orders = ...
// update the totals
foreach(Order order in orders) {
    connection.Execute("update Orders set Total=@Total where Id=@Id", order);
}

This usage becomes particularly interesting when combined with the async API on a connection that is explicitly configured to all "Multiple Active Result Sets" - in this usage, dapper will automatically pipeline the operations, so you aren't paying the latency cost per row. This requires a slightly more complicated usage,

await connection.ExecuteAsync(
    new CommandDefinition(
        "update Orders set Total=@Total where Id=@Id", 
         orders, flags: CommandFlags.Pipelined))

Note, however, that you might also wish to investigate table valued parameters.

Stats

Contributors: 1
2015-11-10
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook